Parse Nginx configuration file

Source: Internet
Author: User
Tags sendfile
: This article describes how to parse the Nginx configuration file. if you are interested in the PHP Tutorial, refer to it. After Nginx is installed, a corresponding installation directory is generated. according to the preceding installation path, the Nginx configuration file path is/opt/nginx/conf, where nginx. conf is the main configuration file of Nginx. Here we will focus on the configuration file nginx. conf.
The Nginx configuration file is mainly divided into four parts: main (global settings), server (host settings), upstream (server load balancer settings), and location (URL matching specific location settings ). The commands set in the main section will affect all other settings. the commands in the server section are mainly used to specify the host and port. the upstream commands are mainly used for load balancing and set a series of backend servers; location is used to match the webpage location. The relationship between the four: server inherits the main, location inherits the server, and upstream neither inherits other settings nor is it inherited.
In these four parts, each part contains several commands. these commands mainly include the main module commands of Nginx, the event module commands, and the HTTP core module commands, at the same time, each part can also use other HTTP module commands, such as the Http SSL module, the HttpGzip Static module, and the Http Addition module.
The following describes the meaning of each Nginx. conf command through an nginx configuration instance. In order to better understand the structure of Nginx and the meaning of each configuration option, the Nginx configuration file is divided into seven parts by function. The following describes these seven parts.

1. global configuration of Nginx
The following section configures the global attribute of Nginx. the code is as follows:

[Html] view plaincopy

  1. User nobody;
  2. Worker_processes 4;
  3. Error_log logs/error. log notice;
  4. Pid logs/nginx. pid;
  5. Worker_rlimit_nofile 65535;
  6. Events {
  7. Use epoll;
  8. Worker_connections 65536;
  9. }


The meaning of each configuration option in the above code is explained as follows:
A user is a master module command that specifies the Nginx Worker process running user and user group. by default, the user is run by the nobody account.
Worker_processes is a master module command that specifies the number of processes to be enabled by Nginx. Each Nginx process consumes an average of 10 Mb ~ 12 MB memory. Based on experience, it is generally enough to specify a 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 master module command used to define a global error log file. The log output levels include debug, info, notice, warn, error, and crit. among them, the debug output logs are the most detailed and the crit output logs are the least.
Pid is a master module command 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 can be opened by an nginx process. The value is 65535. you need to run the "ulimit-n 65535" command to set this parameter.
The events command sets the Nginx working mode and the maximum number of connections.

[Html] view plaincopy

  1. Events {
  2. Use epoll;
  3. Worker_connections 65536;
  4. }


Use is an event Module command used to specify the Nginx working mode. Nginx supports the following working modes: select, poll, kqueue, epoll, rtsig, and/dev/poll. Select and poll are both standard working modes. kqueue and epoll are efficient working modes. The difference is that epoll is used on the Linux platform, while kqueue is used in the BSD system. For Linux systems, epoll is the first choice.
Worker_connections is also an event Module command that defines the maximum number of connections for each Nginx process. The default value 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 used as a reverse proxy, max_clients is changed to max_clients = worker_processes * worker_connections.
The maximum number of processes allowed to open files is limited by the maximum number of Linux system processes. the worker_connections setting takes effect only after the operating system command "ulimit-n 65536" is executed.

2. HTTP server configuration
Next, configure the HTTP server.
The following section describes how to configure the HTTP server attributes in Nginx. the code is as follows:

[Html] view plaincopy

  1. Http {
  2. Include conf/mime. types;
  3. Default_type application/octet-stream;
  4. Log_format main '$ remote_addr-$ remote_user [$ time_local]'
  5. '"$ Request" $ status $ bytes_sent'
  6. '"$ Http_referer" "$ http_user_agent "'
  7. '"$ Gzip_ratio "';
  8. Log_format download '$ remote_addr-$ remote_user [$ time_local]'
  9. '"$ Request" $ status $ bytes_sent'
  10. '"$ Http_referer" "$ http_user_agent "'
  11. '"$ Http_range" "$ sent_http_content_range "';
  12. Client_max_body_size 20 m;
  13. Client_header_buffer_size 32 K;
  14. Large_client_header_buffers 4 32 k;
  15. Sendfile on;
  16. Tcp_nopush on;
  17. Tcp_nodelay on;
  18. Keepalive_timeout 60;
  19. Client_header_timeout 10;
  20. Client_body_timeout 10;
  21. Send_timeout 10;


The following describes the meaning of each configuration option in the code.
Include is a command of the main module. setting the files contained in the configuration file can reduce the complexity of the main configuration file. Similar to the include method in Apache.
Default_type is an HTTP core module instruction. the default type is set to binary stream here, that is, this method is used when the file type is not defined. for example, Nginx is not parsed when the PHP environment is not configured, when you access the php file in a browser, a download window is displayed.
The following code sets the log format.

[Html] view plaincopy

  1. Log_format main '$ remote_addr-$ remote_user [$ time_local]'
  2. '"$ Request" $ status $ bytes_sent'
  3. '"$ Http_referer" "$ http_user_agent "'
  4. '"$ Gzip_ratio "';
  5. Log_format download '$ remote_addr-$ remote_user [$ time_local]'
  6. '"$ Request" $ status $ bytes_sent'
  7. '"$ Http_referer" "$ http_user_agent "'
  8. '"$ Http_range" "$ sent_http_content_range "';


Log_format is the Nginx HttpLog module command used to specify the output format of Nginx logs. Main is the name of the log output format, which can be referenced in the following access_log command.
Client_max_body_size is used to set the maximum number of bytes of a single file that can be requested by the client.
Client_header_buffer_size is used to specify the headerbuffer size from the client request header. For most requests, the buffer size of 1 K is sufficient. if the message header is customized or a larger Cookie exists, the buffer size can be increased. Set this parameter to 32 kB.
Large_client_header_buffers is used to specify the maximum number and size of message headers in the client request. "4" is the number, "128 K" is the size, and the maximum cache volume is 4 kB.
The sendfile parameter is used to enable the efficient file transfer mode. Set the tcp_nopush and tcp_nodelay commands to on to prevent network congestion.
Keepalive_timeout: Set the timeout time for client connection persistence. After this time, the server will close the connection.
Client_header_timeout: Set the timeout value for reading the client request header. If the client has not sent any data after this time, Nginx returns the "Request time out (408)" error.
Client_body_timeout: Set the time-out for client-side request body read. If no data has been sent by the client after this time, Nginx returns the "Request time out (408)" error. the default value is 60.
Send_timeout specifies the timeout time for the response client. This timeout is limited to the time between two connection activities. if the time exceeds this time and the client does not have any activity, Nginx will close the connection.

3. HttpGzip module configuration
Configure the HttpGzip module of Nginx below. This module supports online real-time compression of output data streams. To check whether this module is installed, run the following command:

[Html] view plaincopy

  1. [Root @ localhost conf] #/opt/nginx/sbin/nginx-V
  2. Nginx version: nginx/0.7.65
  3. Configure arguments: -- with-http_stub_status_module -- with-http_gzip_static_module -- prefix =/opt/nginx


You can run the/opt/nginx/sbin/nginx-V command to view the compilation options when installing Nginx. the output shows that the HttpGzip module has been installed.
The following describes how to configure HttpGzip attributes in Nginx configuration:

[Html] view plaincopy

  1. Gzip on;
  2. Gzip_min_length 1 k;
  3. Gzip_buffers 4 16 k;
  4. Gzip_http_version 1.1;
  5. Gzip_comp_level 2;
  6. Gzip_types text/plain application/x-javascript text/css application/xml;
  7. Gzip_vary on;


Gzip is used to enable or disable the gzip module. "gzip on" indicates that GZIP compression is enabled and output data streams are compressed in real time.
The gzip_min_length parameter specifies the minimum number of page bytes that can be compressed. the number of page bytes is obtained from the Content-Length header. The default value is 0, and most pages are compressed. We recommend that you set the size to 1 kb. smaller than 1 KB may increase the pressure.
Gzip_buffers indicates that four memory units of 16 kB are applied for as the compression result stream cache. the default value is to apply for the same memory space as the original data to store gzip compression results.
Gzip_http_version is used to identify the HTTP protocol version. the default value is 1.1. Currently, most browsers support GZIP decompression. use the default value.
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 processing speed is the slowest, which also consumes cpu resources.
Gzip_types is used to specify the compression type. whether or not it is specified, the "text/html" type is always compressed.
The gzip_vary option allows the front-end cache server to cache GZIP-compressed pages, for example, using Squid to cache Nginx-compressed data.

4. server load balancer configuration
The server list of server load balancer is set below.

[Html] view plaincopy

  1. Upstream ixdba.net {
  2. Ip_hash;
  3. Server 192.168.12.133: 80;
  4. Server 192.168.12.134: 80 down;
  5. Server 192.168.12.135: 8009 max_fails = 3 fail_timeout = 20 s;
  6. Server 192.168.12.136: 8080;
  7. }


Upstream is the HTTP Upstream module of Nginx. this module uses a simple scheduling algorithm to achieve load balancing between client IP addresses and backend servers. In the preceding settings, the name of a server load balancer is specified using the upstream command ixdba.net. This name can be specified at will and can be called directly as needed.
The load balancing module of Nginx currently supports four scheduling algorithms, which are described below. the last two are third-party scheduling methods.
Round Robin (default ). Each request is distributed to different backend servers one by one in chronological order. if a backend server goes down, the faulty system is automatically removed, so that user access is not affected.
Invalid Weight. Specify the round-robin Weight. the higher the Weight value, the higher the access probability assigned to it. it is mainly used when the performance of each backend server is uneven.
 Ip_hash. Each request is allocated based on the hash result of the access IP address. in this way, the visitor from the same IP address accesses a backend server at a fixed speed, effectively solving the session sharing problem in the dynamic web page.
Invalid fair. Load balancing algorithms that are more intelligent than the above two. This algorithm intelligently performs load balancing based on the page size and loading time, that is, requests are allocated based on the response time of the backend server, and requests are prioritized for short response time. Nginx does not support fair. to use this scheduling algorithm, you must download the Nginx upstream_fair module.
 Url_hash. Requests are allocated according to the hash result of the access url so that each url is directed to the same backend server, which can further improve the efficiency of the backend cache server. Nginx does not support url_hash. to use this scheduling algorithm, you must install the Nginx hash package.
In the HTTP Upstream module, you can specify the IP address and port of the backend server through the server command, and set the status of each backend server in the server load balancer scheduling. Common statuses include:
Failover down indicates that the current server is not involved in server load balancer.
Slave backup, a reserved backup machine. The backup machine is requested only when all other non-backup machines fail or are busy. Therefore, this machine is under the least pressure.
 Max_fails: the number of failed requests allowed. the default value is 1. If the maximum number of times is exceeded, an error defined by the proxy_next_upstream module is returned.
 Fail_timeout: the service suspension time after the max_fails failure. Max_fails can be used with fail_timeout.
Note that when the load scheduling algorithm is ip_hash, the status of the backend server in the load balancing scheduling cannot be weight or backup.

5. server virtual host configuration
The following describes how to configure a VM. We recommend that you write the content configured for the VM into another file and include it through the include command, which is easier to maintain and manage.

[Html] view plaincopy

  1. Server {
  2. Listen 80;
  3. Server_name 192.168.12.188 www.ixdba.net;
  4. Index index.html index.htm index. jsp;
  5. Root/web/wwwroot/www.ixdba.net
  6. Charset gb2312;


The server Mark defines the start of the VM. listen is used to specify the service port of the VM. server_name is used to specify the IP address or domain name. multiple domain names are separated by spaces. Index is used to set the default homepage address for access. The root command is used to specify the web page root directory of the VM. this directory can be a relative or absolute path. Charset is used to set the default encoding format of the webpage.
Access_log logs/www.ixdba.net. access. log main;
Access_log is used to specify the path for storing access logs of the virtual host, and the final main is used to specify the output format of access logs.

6. URL matching configuration
URL matching is the most flexible part in Nginx configuration. Location supports regular expression matching and condition matching. you can use the location command to filter dynamic and static webpages.
All the static files ending with the expires are handed over to nginx for processing, and expires is used to specify the expiration time of the static file, which is 30 days.

[Html] view plaincopy

  1. Location ~ . * \. (Gif | jpg | jpeg | png | bmp | swf) $ {
  2. Root/web/wwwroot/www.ixdba.net;
  3. Expires 30d;
  4. }


In the following section, all files under upload and html are handed over to nginx for processing. of course, the upload and html directories are included in the/web/wwwroot/www.ixdba.net directory.

[Html] view plaincopy

  1. Location ~ ^/(Upload | html )/{
  2. Root/web/wwwroot/www.ixdba.net;
  3. Expires 30d;
  4. }


In the last section, location is the filtering of dynamic web pages under the virtual host, that is, all files suffixed with. jsp are handed over to port 8080 of the local machine for processing.

[Html] view plaincopy

  1. Location ~ . *. Jsp $ {
  2. Index. jsp;
  3. Proxy_pass http: // localhost: 8080;
  4. }


7. StubStatus module configuration
The StubStatus module can obtain the working status of Nginx since it was last started. this module is a non-core module that must be manually specified during Nginx compilation and installation.
The following commands enable the function of obtaining the Nginx working status.

[Html] view plaincopy

  1. Location/NginxStatus {
  2. Stub_status on;
  3. Access_log logs/NginxStatus. log;
  4. Auth_basic "NginxStatus ";
  5. Auth_basic_user_file ../htpasswd;
  6. }


Stub_status is set to "on", which indicates that the StubStatus statistical function is enabled. Access_log is used to specify the access log file of the StubStatus module. Auth_basic is an authentication mechanism for Nginx. Auth_basic_user_file is used to specify the authentication password file. because Nginx auth_basic authentication uses a password file compatible with Apache, you need to use Apache's htpasswd command to generate the 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 webadmin
The following message is displayed:
New password:
After you enter the password, the system will require you to enter the password again. The user is added after confirmation.

To view the running status of Nginx, enter http: // ip/NginxStatus and enter the username and password you just created. the following information is displayed:
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 row indicate that Nginx has processed a total of 393411 connections, successfully created 393411 handshakes, and processed a total of 393799 requests. The last row of Reading indicates the number of headers that Nginx reads to the client, Writing indicates the number of headers that Nginx returns to the client, and "Waiting" indicates that Nginx has completed processing, the number of resident connections waiting for the next request.

In the last section, the error response page of the VM is set. you can use the error_page command to customize the return page of various error messages. By default, Nginx searches for the specified returned page in the html Directory of the main directory. Note that the returned page size of these error messages must exceed 512 KB, otherwise, the default error page of ie will be replaced by ie.

[Html] view plaincopy

  1. Error_page 404/404 .html;
  2. Error_page 500 502 503 x.html;
  3. Location =/50x.html {
  4. Root html;
  5. }
  6. }
  7. }


For more information, see "technical achievement dream" blog, http://ixdba.blog.51cto.com/2895551/790611

The above describes how to parse the Nginx configuration file, including some content, and hope to be helpful to friends who are interested in the PHP Tutorial.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.