Parse Nginx configuration file
Release: 2016-08-08 09:31:31
Original
1027 people have browsed it
After Nginx is installed, the corresponding installation directory will be generated. According to the previous installation path, the Nginx configuration file path is /opt/nginx/conf, where nginx.conf is the main configuration file of Nginx. Here we focus on the nginx.conf configuration file. Nginx configuration file is mainly divided into four parts: main (global settings), server (host settings), upstream (load balancing server settings) and location (URL matches settings for a specific location). The instructions set in the main part will affect all other settings; the instructions in the server part are mainly used to specify the host and port; the upstream instructions are mainly used for load balancing and setting up a series of back-end servers; the location part is used to match the location of the web page. The relationship between the four: server inherits main, location inherits server, and upstream will neither inherit other settings nor be inherited.中 Among these four parts, each part contains several instructions. These instructions mainly include Nginx's main module instructions, event module instructions, HTTP core module instructions, and each part can also use other HTTP module instructions, such as instructions, such as Http SSL module, HttpGzip Static module and Http Addition module, etc. The following uses an Nginx configuration example to introduce the meaning of each instruction in nginx.conf in detail. In order to have a clearer understanding of the structure of Nginx and the meaning of each configuration option, the Nginx configuration file is divided into 7 parts according to the function points and explained one by one. The following is an introduction around these 7 parts. 1. Global configuration of Nginx
The following content is the global attribute configuration of Nginx. The code is as follows:
[html] view
plaincopy
user nobody nobody; -
worker_processes 4;
-
error_log logs/error.log notice;
-
pid Logs/nginx.pid;
-
worker_rlimit_nofile 65535;
- events{
-
use epoll;
-
worker_connections 65536;
-
}
The meaning of each configuration option in the above code is explained as follows:
user is a master Module directive, specifying the user and user group for running the Nginx Worker process. By default, it is run by the nobody account.
worker_processes is a main module instruction that specifies the number of processes to be opened by Nginx. Each Nginx process consumes an average of 10M~12M of memory. According to experience, it is generally enough to specify one process. If it is a multi-core CPU, it is recommended to specify the same number of processes as the number of CPUs.
error_log is a main module directive used to define global error log files. Log output levels include debug, info, notice, warn, error, and crit to choose from. Among them, debug output log is the most detailed, while crit output log is the least.
pid is a main module instruction, used to specify the storage file location of the process id.
worker_rlimit_nofile is used to specify the maximum number of file descriptors that an nginx process can open. Here it is 65535. You need to use the command "ulimit -n 65535" to set it. The
events command is to set the working mode of Nginx and the upper limit of the number of connections.
[html] view
plaincopy
events{ -
use epoll;
-
worker_connections 65536;
-
}
-
use is an event module command used to specify the working mode of Nginx. The working modes supported by Nginx are select, poll, kqueue, epoll, rtsig and /dev/poll. Among them, select and poll are standard working modes, and kqueue and epoll are efficient working modes. The difference is that epoll is used on the Linux platform, while kqueue is used on the BSD system. For Linux systems, the epoll working mode is the first choice.
worker_connections is also an event module directive, used to define the maximum number of connections for each Nginx process. The default is 1024. The maximum number of client connections is determined by worker_processes and worker_connections, that is, Max_client=worker_processes*worker_connections, when acting as a reverse proxy , max_clients becomes: max_clients
= worker_processes * worker_connections/4.
The maximum number of connections of a process is limited by the maximum number of open files of the Linux system process. The setting of worker_connections can only take effect after executing the operating system command "ulimit -n 65536". 2. HTTP server configuration
Next, start the HTTP server settings.
The following content is Nginx’s configuration of HTTP server-related attributes. The code is as follows:
[html] view
plaincopy
- http{
- include conf/mime.types;
- default_type application/octet-stream;
- log_formatmain '$remote_addr - $remote_user [$time_local] '
- '"$request" $status $bytes_sent ' '
- '"$http_referer" "$http_user_agent" ' '"$gzip_ratio"';
- log_form at download '$remote_addr - $remote_user [ $time_local] '
- '"$request" $status $bytes_sent '
- '"$http_referer" "$http_user_agent" '
- '"$http_range" "$sent_http_content_range" ';
- client_max_body_size 20m;
- client_header_buffer_size 32K;
- large_client_header_buffers 4 32k;
- Sendfile on;
- tcp_nopush on;
- tcp_nodelay on;
-
keepalive_timeout 60; client_header_timeout 10;
-
client_body_timeout 10;
-
send_timeout 10;
- The following is a detailed introduction to each configuration option in this code meaning. include is a main module instruction that enables the setting of files included in the configuration file, which can reduce the complexity of the main configuration file. Similar to the include method in Apache. default_type belongs to the HTTP core module directive. Here, the default type is set to binary stream, which is used when the file type is not defined. For example, when the PHP environment is not configured, Nginx will not parse it. At this time, use Browse When the PHP file is accessed by the server, a download window will appear.
The code below implements the setting of the log format.
[html] view
plaincopy
MLog_Format Main' $ Remote_ADDR-$ Remote_user [$ Time_local] '
' "$ Request" $ Status $ Bytes_SENT '
' "$ http_referr" $ http_user_agent "'
- '"$gzip_ratio"';
- log_format download '$remote_addr - $remote_user [$time_local] '
- '"$request" $status $bytes_sent '
- '"$http_referer" " $http_user_agent" '
- '"$http_range" "$sent_http_content_range"';
-
log_format is Nginx’s HttpLog module instruction, used to specify the output format of Nginx logs. mainThe name of this log output format, which can be referenced in the access_log directive below.
client_max_body_size is used to set the maximum number of bytes of a single file allowed to be requested by the client.
client_header_buffer_size is used to specify the headerbuffer size from the client request header. For most requests, a buffer size of 1K is sufficient. If you customize the message headers or have larger cookies, you can increase the buffer size. This is set to 32K.
large_client_header_buffers is used to specify the maximum number and size of caches for larger message headers in client requests. "4" is the number, "128K" is the size, and the maximum cache amount is 4 128K.
The sendfile parameter is used to enable efficient file transfer mode. Set the tcp_nopush and tcp_nodelay instructions to on to prevent network blocking.
keepalive_timeout sets the timeout for client connections to stay alive. After this time has elapsed, the server will close the connection.
client_header_timeout sets the client request header reading timeout. If this time is exceeded and the client has not sent any data, Nginx will return a "Request time out (408)" error.
client_body_timeout sets the client request body reading timeout. If this time is exceeded and the client has not sent any data, Nginx will return a "Request time out (408)" error. The default value is 60.
send_timeout specifies the timeout period for responding to the client. This timeout is limited to the time between two connection activities. If this time is exceeded without any activity on the client, Nginx will close the connection. 3.HttpGzip module configuration
Configure Nginx’s HttpGzip module below. This module supports online real-time compression of output data streams. To check whether this module is installed, you need to use the following command:
[html] view
plaincopy
- [root@localhost conf]# /opt/nginx/sbin/nginx -V
- nginx version: nginx/0.7.65
- configure arguments: --with-http _stub_status_module -- with-http_gzip_static_module --prefix=/opt/nginx
Use the /opt/nginx/sbin/nginx -V command to view the compilation options when installing Nginx. From the output, we can see that we have installed it HttpGzip module.
The following are the relevant attribute settings of the HttpGzip module in the Nginx configuration:
[html] view
plaincopy
- gzip on;
- gzip_min_length 1k;
- gzip_buffers 4 16k;
- g zip_http_version 1.1;
- gzip_comp_level 2;
- gzip_types text/plain application/x -javascript text/css application/xml;
- gzip_vary on;
gzip is used to set the gzip module on or off. "gzip on" means turning on GZIP compression and compressing the output data stream in real time.
gzip_min_length sets the minimum number of bytes of the page allowed for compression. The number of page bytes is obtained from the Content-Length of the header. The default value is 0, which compresses the page regardless of its size. It is recommended to set the number of bytes to be greater than 1K. If it is less than 1K, the number of bytes may become larger and larger.
gzip_buffers means applying for 4 units of 16K memory as the compression result stream cache. The default value is to apply for the same memory space as the original data size to store the gzip compression result.
gzip_http_version is used to set and identify the HTTP protocol version. The default is 1.1. Currently, most browsers already support GZIP decompression, so just use the default.
gzip_comp_level is used to specify the GZIP compression ratio. 1 has the smallest compression ratio and the fastest processing speed; 9 has the largest compression ratio and fast transmission speed, but the slowest processing and consumes more CPU resources.
gzip_types is used to specify the compression type. Regardless of whether it is specified or not, the "text/html" type will always be compressed.
The gzip_vary option allows the front-end cache server to cache GZIP-compressed pages, such as using Squid to cache Nginx-compressed data. 4. Load balancing configuration
Set the load balancing server list below.
[html] view
plaincopy
- upstream ixdba.net{
- ip_hash;
- server 192.168.12.133:80;
- server 1 92.168.12.134:80 down;
- server 192.168.12.135: 8009 max_fails=3 fail_timeout=20s;
- server 192.168.12. 136:8080;
- }
upstream is from Nginx HTTP Upstream module, this module uses a simple scheduling algorithm to achieve load balancing from the client IP to the back-end server. In the above settings, the name of a load balancer ixdba.net is specified through the upstream directive. This name can be specified arbitrarily and can be called directly where needed later.
Nginx’s load balancing module currently supports 4 scheduling algorithms, which are introduced below. The last two are third-party scheduling methods.
Polling (default). Each request is assigned to different back-end servers one by one in chronological order. If a back-end server goes down, the faulty system is automatically eliminated so that user access is not affected.
Weight. Specify the polling weight. The larger the Weight value, the higher the access probability allocated. It is mainly used when the performance of each back-end server is uneven.
ip_hash. Each request is allocated according to the hash result of the accessed IP, so that visitors from the same IP can access a back-end server, which effectively solves the session sharing problem of dynamic web pages.
fair. A more intelligent load balancing algorithm than the above two. This algorithm can intelligently perform load balancing based on page size and loading time, that is, allocate requests based on the response time of the back-end server, and prioritize those with short response times. Nginx itself does not support fair. If you need to use this scheduling algorithm, you must download the upstream_fair module of Nginx.
url_hash. Distributing requests according to the hash result of the accessed URL so that each URL is directed to the same backend server can further improve the efficiency of the backend cache server. Nginx itself does not support url_hash. If you need to use this scheduling algorithm, you must install the Nginx hash software package.
In the HTTP Upstream module, you can specify the IP address and port of the backend server through the server command, and you can also set the status of each backend server in load balancing scheduling. Commonly used states are:
down, which means that the current server does not participate in load balancing for the time being.
backup, reserved backup machine. The backup machine will be requested when all other non-backup machines fail or are busy, so this machine has the least pressure.
max_fails, the number of allowed request failures, defaults to 1. When the maximum number of times is exceeded, the error defined by the proxy_next_upstream module is returned.
fail_timeout, the time to suspend the service after max_fails failures. max_fails can be used together with fail_timeout.
Note: When the load scheduling algorithm is ip_hash, the status of the backend server in load balancing scheduling cannot be weight and backup. 5.server virtual host configuration
The following introduces the configuration of the virtual host. It is recommended to write the configuration content of the virtual host into another file and then include it through the include directive, which makes maintenance and management easier.
[html] view
plaincopy
- server{
- listen 80;
-
server_name 192.168.12.188 www.ixdba.net;
- index index.html index.htm index.jsp;
- root /web/wwwroot/www.ixdba.net
- charset gb2312;
The server flag defines the start of the virtual host, listen is used to specify the service port of the virtual host, server_name is used to specify the IP address or domain name, and multiple domain names are separated by spaces. Index is used to set the default home page address for access, and the root command is used to specify the web page root directory of the virtual host. This directory can be a relative path or an absolute path. Charset is used to set the default encoding format of web pages.
access_log logs/www.ixdba.net.access.log main;
access_log is used to specify the access log storage path of this virtual host, and the last main is used to specify the output format of the access log. 6.URL matching configuration
URL address matching is the most flexible part of Nginx configuration. Location supports regular expression matching and conditional judgment matching. Users can use the location directive to implement Nginx filtering of dynamic and static web pages.
The following setting uses the location directive to analyze and process the web page URL. All static files with extensions ending in .gif, .jpg, .jpeg, .png, .bmp, and .swf are handed over to nginx for processing, and expires Used to specify the expiration time of static files, here it is 30 days.
[html] view
plaincopy
- location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {
-
- 这}
-
The following settings are handed over to all files under UPLOAD and HTML to Nginx for processing. Of course, the UPLOAD and HTML directory are included in /web/wwwroot/www.ixdba.net directory middle.
plaincopy
location ~ ^/(upload|html)/ {
expires 30d;
- In the last setting, location is the filtering process for dynamic web pages under this virtual host, that is, all files with the .jsp suffix are handed over to the 8080 port of the local machine for processing.
[html] view
plaincopy
- location ~ .*.jsp$ {
-
index index.jsp;
proxy_pass http://localhost:8080;
}
- 7. StubStatus module configuration The StubStatus module can obtain the working status of Nginx since the last startup. This module is not a core module and needs to be manually specified when Nginx is compiled and installed to use this function.
- The following command actually specifies to enable the function of obtaining Nginx working status.
[html] view
plaincopy
- location /NginxStatus {
- stub_status on;
- access_log logs/NginxStatus.log;
- htpasswd;
- }
stub_status is set to "on" to enable the working status statistics function of StubStatus. access_log is used to specify the access log file of the StubStatus module. auth_basic is an authentication mechanism of Nginx. auth_basic_user_file is used to specify the password file for authentication. Since Nginx's auth_basic authentication uses a password file that is compatible with Apache, you need to use Apache's htpasswd command to generate a password file. For example, to add a webadmin user, you can use the following method to generate a password file. :
/usr/local/apache/bin/htpasswd -c /opt/nginx/conf/htpasswd webadminYou will get the following prompt message:New password:After entering the password, the system will ask you to enter the password again. After confirmation, the user is added successfully.
To check the running status of Nginx, you can enter http://ip/ NginxStatus, then enter the username and password you just created to see the following information:
Active connections: 1
server accepts handled requests
393411 393411 393799 Reading: 0 Writing: 1 Waiting: 0
Active connections indicates the number of currently active connections. The three numbers in the third line indicate that Nginx has currently processed a total of 393411 connections, successfully created 393411 handshakes, and processed a total of 393799 requests. . Reading in the last line indicates the number of client header information read by Nginx. Writing indicates the number of header information returned to the client by Nginx. "Waiting" indicates the number of resident connections that Nginx has completed processing and is waiting for the next request instruction.
In the last setting, the error message return page of the virtual host is set. The return page of various error messages can be customized through the error_page command. By default, Nginx will search for the specified return page in the HTML directory of the home directory. It is particularly important to note that the size of the return page for these error messages must exceed 512K, otherwise it will be replaced by the IE browser's default Error page.
[html] view
plaincopy
404.html;
location = /50x.html { -
root html;
-
Technology Makes Dreams. 1/790611
-
The above introduces the parsing of Nginx configuration files, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31