Parse Nginx configuration file

Source: Internet
Author: User
Tags epoll sendfile
after installation of Nginx, the corresponding installation directory will be generated, according to the previous installation path, nginx configuration file path is/opt/nginx/conf, where nginx.conf is the main configuration file nginx. The following nginx.conf this configuration file is highlighted here.
nginx profiles are divided into four main parts: main (global setting), Server (host settings), upstream (Load balancer server settings), and location (URL matches settings at specific locations). The instructions set in the main section affect all other settings, and the server part of the instruction is used primarily for specifying the host and port; the upstream instruction is primarily used for load balancing, setting up a series of back-end servers, and the Location section for matching page locations. The relationship between the four: the server Inherits Main,location inheritance Server,upstream neither inherits other settings nor inherits them.
in each of these four sections, each part contains instructions that mainly contain Nginx's main module directives, Event module directives, HTTP Core module directives, and each section can also use other HTTP module directives, such as the HTTP SSL module, Httpgzip static modules and HTTP addition modules.
Below is an example of Nginx configuration, detailing the meaning of each instruction under nginx.conf. In order to better understand the structure of nginx and the meaning of each configuration option here, the Nginx configuration file is divided into 7 sections, followed by a function point, which is described around these 7 sections.

Global configuration for 1.Nginx
The following section is the global property configuration for Nginx, the code is as follows:

[HTML] View plaincopy

    1. User nobody 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 meanings of each configuration option in the preceding code are explained below:
User is a master module directive that specifies the Nginx worker process running users and user groups, which are run by default by the nobody account.
worker_processes is a master module directive that specifies the number of processes that Nginx will open. Each nginx process consumes 10m~12m memory on average. Based on experience, it is generally sufficient to specify a process, and if it is a multicore CPU, it is recommended to specify the same number of processes as the CPU.
Error_log is a master module directive used to define a global error log file. The log output levels are debug, info, notice, warn, error, crit, where debug output logs are the most verbose, and crit output logs are minimal.
The pid is a master module directive that specifies the location of the file where the process ID is stored.
The worker_rlimit_nofile is used to specify the maximum number of file descriptors a Nginx process can open, which is 65535 and needs to be set using the command "Ulimit-n 65535".
The events command sets the operating mode of nginx and the maximum number of connections.

[HTML] View plaincopy

    1. events{
    2. Use Epoll;
    3. Worker_connections 65536;
    4. }


use is an event module directive that specifies Nginx's operating mode. The working modes supported by Nginx are SELECT, poll, Kqueue, Epoll, Rtsig and/dev/poll. Both select and poll are standard working modes, kqueue and epoll are efficient modes of operation, unlike Epoll used on Linux platforms and Kqueue in BSD systems. For Linux systems, the Epoll mode of operation is preferred.
Worker_connections is also an event module directive that defines the maximum number of connections per session for Nginx, which defaults to 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 for a process is limited by the maximum number of open files for the Linux system process, and the settings worker_connections after the operating system command "Ulimit-n 65536" take effect.

2.HTTP Server Configuration
Next, start the HTTP server setup.
The following section is the Nginx configuration of the HTTP server-related properties, 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 20m;
  13. Client_header_buffer_size 32K;
  14. Large_client_header_buffers 4 32k;
  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 meanings of each configuration option in this code are described in more detail below.
Include is a master module directive that enables you to set the files contained in the configuration file, reducing the complexity of the master configuration file. Similar to the Include method in Apache.
Default_type belongs to the HTTP Core Module directive, where the default type is a binary stream, that is, when the file type is not defined when the use of this way, for example, when the PHP environment is not configured, Nginx is not resolved, at this time, the browser to access the PHP file will appear in the Download window.
The following code implements the setting of 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";


The Log_format is an nginx httplog module instruction that specifies the output format of the Nginx log. Main the name of the output format for this log, which can be referenced in the following Access_log directive.
The client_max_body_size is used to set the maximum number of individual file bytes allowed for client requests.
The client_header_buffer_size is used to specify the Headerbuffer size from the client request header. For most requests, the buffer size of 1K is sufficient, and if you customize the message header or have a larger cookie, 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 large headers in a client request, "4" is the number, "128K" is the size, and the maximum cache volume is 4 128K.
The sendfile parameter is used to turn on efficient file transfer mode. Set the Tcp_nopush and tcp_nodelay two instructions to on to prevent network congestion.
Keepalive_timeout Sets the time-out for client connections to remain active. After this time is exceeded, the server shuts down the connection.
Client_header_timeout Sets the client request header read time-out. If the client has not sent any data over this time, Nginx will return the "Request Time Out (408)" error.
Client_body_timeout Sets the client request principal read time-out. If this time is exceeded, the client has not sent any data, and Nginx returns the "Request Time Out (408)" error, which is the default value of 60.
The send_timeout specifies the time-out for responding to the client. This timeout is limited to the time between two connection activities, and if the client does not have any activity at this time, Nginx will close the connection.

3.HttpGzip Module Configuration
Configure the Nginx httpgzip module below. This module supports on-line real-time compressed output data stream. To see if this module is installed, you need to use 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


The /opt/nginx/sbin/nginx-v command allows you to view the compile options when installing Nginx, and the output shows that we have installed the Httpgzip module.
The following are the related property settings for the Httpgzip module in Nginx configuration:

[HTML] View plaincopy

    1. gzip on;
    2. Gzip_min_length 1k;
    3. Gzip_buffers 4 16k;
    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 set the Gzip module on or off, "gzip on" means to turn on gzip compression and compress the output data stream in real time.
Gzip_min_length Sets the minimum number of bytes of pages that are allowed to compress, and the number of page bytes is obtained from the header content-length. The default value is 0, regardless of how much of the page is compressed. It is recommended to set the number of bytes greater than 1K, which may be more or less larger than 1K.
Gzip_buffers represents the request for 4 units of 16K of memory as a compressed result stream cache, the default value is to request the same amount of memory space as the original data to store gzip compression results.
gzip_http_version is used to set the recognition HTTP protocol version, default is 1.1, most browsers now support Gzip decompression, using the default.
Gzip_comp_level is used to specify gzip compression ratio, 1 compression ratio is minimal, processing speed is the fastest, 9 compression ratio is the largest, transmission speed, but processing the slowest, but also consumes CPU resources.
gzip_types is used to specify the type of compression, regardless of whether 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, such as using squid to cache nginx-compressed data.

4. Load Balancing Configuration
The following sets the list of servers for load balancing.

[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= 20s;
    6. Server 192.168.12.136:8080;
    7. }


upstream is the Nginx HTTP upstream module, which uses a simple scheduling algorithm to load balance client IP to back-end servers. In the above settings, a load balancer name ixdba.net is specified by the upstream directive. This name can be arbitrarily specified, and will be called directly in the following areas.
nginx Load Balancer module currently supports 4 scheduling algorithms, the following are described separately, the latter two are third-party scheduling methods.
 Polling (default). Each request is individually assigned to a different back-end server in chronological order, and if a server on the backend is down, the fault system is automatically rejected, leaving the user's access unaffected.
weight. Specifies the polling weights, the higher the weight value, the higher the access probability assigned to it, which is primarily used in the case of uneven performance on the backend per server.
ip_hash. Each request is allocated according to the hash result of the access IP, so that visitors from the same IP have fixed access to a back-end server, which effectively solves the session sharing problem of dynamic Web pages.
fair. More intelligent load balancing algorithms than the two above. This algorithm can intelligently load balance according to the page size and the load time, that is, the response time of the backend server to allocate the request, the response time is short priority allocation. Nginx itself is not support fair, if you need to use this scheduling algorithm, you must download the Nginx Upstream_fair module.
url_hash. The efficiency of the back-end cache server can be further improved by assigning requests by the hash result of the access URL, which directs each URL to the same back-end server. Nginx itself is not support url_hash, if you need to use this scheduling algorithm, you must install Nginx hash package.
In the HTTP upstream module, you can specify the IP address and port of the back-end server through the server directives, and you can also set the state of each back-end server in the load-balancing schedule. The commonly used statuses are:
down, which indicates that the current server is temporarily not participating in load balancing.
backup, reserved for the backup machine. When all other non-backup machines fail or are busy, the backup machine is requested, so the pressure on this machine is the lightest.
max_fails, the number of times a request failed to be allowed, by default, 1. Returns the error defined by the Proxy_next_upstream module when the maximum number of times is exceeded.
fail_timeout, the time to suspend service after a max_fails failure. Max_fails can be used with fail_timeout.
Note that when the load scheduling algorithm is Ip_hash, the state of the backend server in load balancing scheduling cannot be weight and backup.

5.server Virtual Host Configuration
The configuration of the virtual host is described below. It is recommended that the contents of the configuration of the virtual host be written into another file and then included through the include directive, 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 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 address of the access, and the root command is used to specify the Web root of the virtual host, which can either be a relative path or an absolute path. CharSet is used to set the default encoding format for Web pages.
access_log Logs/www.ixdba.net.access.log main;
The Access_log is used to specify the access log storage path for 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, also supports conditional judgment matching, user can use location instruction to implement Nginx dynamic, static Web page filtering processing.
The following setting uses the location directive to parse the URL of a Web page, all static files with a. gif,. jpg,. jpeg,. png,. bmp,. swf,. Expires,. This 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. }


The following setting is for all files under upload and HTML to be handled by Nginx, of course, 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 this final setting, location is the filtering process for dynamic Web pages under this virtual host, which means that all files with the. jsp suffix are given to the native 8080 port processing.

[HTML] View plaincopy

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


7.StubStatus Module Configuration
The Stubstatus module is capable of obtaining Nginx's working status since the last boot, this module is not a core module and needs to be specified manually to use this feature at Nginx compilation installation.
The following instructions specify the ability to enable the get Nginx working state.

[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" to enable Stubstatus's work status statistics feature. The access_log is used to specify the access log file for the Stubstatus module. Auth_basic is an authentication mechanism of nginx. Auth_basic_user_file used to specify the authentication password file, because the Nginx auth_basic authentication uses the Apache compatible password file, therefore needs to use the Apache htpasswd command to generate the password file, For example, to add a WebAdmin user, you can generate a password file using the following method:
/usr/local/apache/bin/htpasswd-c/opt/nginx/conf/htpasswd WebAdmin
You will get the following message:
New Password:
After entering your password, you will be asked to enter your password again. Add user success after confirmation.

To view Nginx's running status, you can enter Http://ip/NginxStatus and enter the user name 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 represents the number of currently active connections, and the third row of three numbers indicates that Nginx is currently processing 393,411 connections, successfully creating 393,411 handshakes, and processing 393,799 requests altogether. The last line of reading represents the Nginx read to the client header information, writing represents the number of header information returned to the client, "Waiting" indicates that Nginx has finished processing, is waiting for the next request instruction when the number of resident connections.

In the last set, the error information of the virtual host is set back to the page, and the error_page instruction can be used to customize the return page of various error messages. By default, Nginx will be in the home directory of the HTML directory to find the specified return page, in particular, the return page size of these error messages must be more than 512K, the person will be replaced by IE browser default error page ie.

[HTML] View plaincopy

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


See "Technology Achievement Dream" blog, http://ixdba.blog.51cto.com/2895551/790611

The above describes the parsing nginx configuration file, including the aspects of the content, I hope the PHP tutorial interested in a friend helpful.

  • 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.