nginx configuration file

1, Structure of nginx configuration file

1. The general structure is as follows

...              #Global block

events {         #events block
   ...
}

http      #http block
{
    ...   #http global block
    server        #server block
    { 
        ...       #server global block
        location [PATTERN]   #location block
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http global block
}

Global block: configure instructions that affect nginx global. Generally, there are user groups running nginx server, pid storage path of nginx process, log storage path, introduction of configuration file, number of worker process es allowed to be generated, etc. For example:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events block: the configuration affects the nginx server or the network connection with the user. There is the maximum number of connections per process, which event driven model is selected to process connection requests, whether multiple network connections are allowed to be accepted at the same time, and starting multiple network connection serialization.

events
{
    #Refer to the event model, use [kqueue | rtsig | epoll | / dev / poll | select | poll]; Epoll model is a high-performance network I/O model in Linux kernel above 2.6. If it runs on FreeBSD, kqueue model is used
    use epoll;
    #Maximum connections of a single process (maximum connections = connections * processes)
    worker_connections 1024;    #The maximum number of connections is 512 by default
}

http block: it can nest multiple server s, configure most functions such as proxy, cache and log definition, and configure third-party modules. Such as file import, MIME type definition, log customization, whether to use sendfile to transfer files, connection timeout, number of single connection requests, etc.

http
{
    include mime.types; #File extension and file type mapping table
    default_type application/octet-stream; #Default file type
    #charset utf-8; #Default encoding
    server_names_hash_bucket_size 128; #hash table size of server name
    client_header_buffer_size 32k; #Upload file size limit
    large_client_header_buffers 4 64k; #Set request delay
    client_max_body_size 8m; #Set request delay
    keepalive_timeout 65;  #The connection timeout, which is 75s by default, can be set in http, server and location blocks.
    # Open directory list access and download the appropriate server. It is closed by default
    autoindex on; # display contents
    autoindex_exact_size on; # The default display file size is on. The exact size of the file is displayed in bytes. After changing to off, the approximate size of the file is displayed in kB, MB or GB
    autoindex_localtime on; # The displayed file time is off by default. The displayed file time is GMT. after the time is changed to on, the displayed file time is the server time of the file
    
    sendfile on; # Turn on the efficient file transfer mode. The sendfile instruction specifies whether nginx calls the sendfile function to output files. For ordinary applications, it is set to on. If it is used for downloading and other applications, it can be set to off to balance the disk and network I/O processing speed and reduce the system load. Note: if the picture is abnormal, change this to off
    tcp_nopush on; # Prevent network congestion
    tcp_nodelay on; # Prevent network congestion
    
    # FastCGI related parameters are used to improve the performance of the website: reduce resource occupation and improve access speed. The following parameters can be understood literally
    fastcgi_connect_timeout 300; ## link
    fastcgi_send_timeout 300;  ##Reading refers to the timeout of the whole process of sending a request from the nginx process to the fastcgi process
    fastcgi_read_timeout 300;  ##Sending a request refers to the timeout of the whole process of sending a response from the fastcgi process to the nginx process
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    
    # gzip module settings
    gzip on; #Turn on gzip compressed output
    gzip_min_length 1k; #The minimum number of bytes of the page allowed to be compressed. The number of bytes of the page is obtained from the content length stolen from the header. The default is 0. No matter how many pages are compressed. It is recommended to set the number of bytes greater than 1k. If it is less than 1k, it may be more compressed
    gzip_buffers 4 16k; #It means that four 16k memory units are applied as the compression result stream cache. The default value is to apply the same memory space as the original data size to store gzip compression results
    gzip_http_version 1.1; #Compressed version (the default is 1.1. At present, most browsers already support gzip decompression. If the front end is squid2.5, please use 1.0)
    gzip_comp_level 2; #Compression level. 1 the compression ratio is the smallest and the processing speed is fast. 9 the compression ratio is the largest, which consumes cpu resources and the processing speed is the slowest. However, because the compression ratio is the largest, the packet is the smallest and the transmission speed is fast
    gzip_types text/plain application/x-javascript text/css application/xml;
    #The compression type contains text/html by default, so there is no need to write it below. There will be no problem writing it, but there will be a warn
    gzip_vary on;#This option allows the front-end cache server to cache gzip compressed pages. For example, squid can be used to cache nginx compressed data
    
    #You need to use it to limit the number of IP connections
    #limit_zone crawler $binary_remote_addr 10m;
    
    ##upstream load balancing, four scheduling algorithms

server block: configure the relevant parameters of the virtual host. There can be multiple servers in one http.

#Configuration of virtual host
    server
    {
        # Listening port
        listen 80;
        # There can be multiple domain names separated by spaces
        server_name 127.0.0.1;
        # HTTP auto jump to HTTPS
        rewrite ^(.*) https://www.baidu.com;
        deny 127.0.0.1;  #Rejected ip
        allow 172.18.5.54; #Allowed ip 
    }
    upstream myserver {   
      server 127.0.0.1:8080;
      server 192.168.24.189:8080 backup;  #Hot standby
    }
    server
    {
        # Listening port HTTPS
        listen 443 ssl;
        server_name https://www.baidu.com;
        root /data/www/;
        # Configure domain name certificate
        ssl_certificate      C:\WebServer\Certs\certificate.crt;
        ssl_certificate_key  C:\WebServer\Certs\private.key;
        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;
        ssl_protocols SSLv2 SSLv3 TLSv1;
        ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
        ssl_prefer_server_ciphers  on;
    
        index index.html index.htm index.php;
        
        location ~ .*\.(php|php5)?$
        {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi.conf;
        }

location block: configure the routing of requests and the processing of various pages.

# Configure address interception and forwarding to solve the problem of cross domain authentication
        location /oauth/{
            proxy_pass https://localhost:13580/oauth/;
            proxy_set_header HOST $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
        
        # Picture cache time setting
        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
            expires 10d;
        }
        
        # JS and CSS cache time settings
        location ~ .*\.(js|css)?$ {
            expires 1h;
        }

# Log format setting
        log_format access '$server_name $remote_addr -$remote_user [$time_local] "$request"'
                  '$status $uptream_status $body_bytes_sent "$http_referer"'
                  '"$http_user_agent" "$http_x_forwarded_for" '
                  '$ssl_protocol $ssl_cipher $upstream_addr $request_time $upstream_response_time';
       # Define the access log of this virtual host
        access_log /var/log/nginx/access.log access;
        
        # Set the address to view the status of Nginx. The StubStatus module can obtain the working status of Nginx since it was last started. This module is not a core module and needs to be manually specified during the compilation and installation of Nginx
        location /NginxStatus {
            stub_status on;
            access_log on;
            auth_basic "NginxStatus";
            auth_basic_user_file conf/htpasswd;
            #The contents of the htpasswd file can be generated using the htpasswd tool provided by apache
        }
    }
}

2, Matching rules for location

1. Set nginx virtual directory by alias and root

  1. The directory specified by alias is accurate, that is, the files in the path directory accessed by location matching are directly found in the alias directory;
  2. The directory specified by root is the upper level directory of the path directory accessed by location matching. This path directory must really exist under the directory specified by root;
  3. rewrite break cannot be used in the directory block with alias tag; In addition, the directory specified by alias must be followed by "/"!!
  4. In the alias virtual directory configuration, if the path directory matching the location is not followed by "/", whether to add "/" to the path directory in the accessed url address will not affect the access, and it will automatically add "/" when accessing;
  5. However, if "/" is added after the path directory matching the location, then "/" must be added to the path directory in the url address to be accessed, and "/" will not be added automatically during access. If "/" is not added, the access will fail!
  6. In the root directory configuration, whether the path directory matching location is followed by "/" or not will not affect access.
server {
          listen 80;
          server_name www.wangshibo.com;
          index index.html index.php index.htm;
          access_log /usr/local/nginx/logs/image.log;

    location / {
        root /var/www/html;
        }

   location /haha {                                          //The matching path directory haha does not need to exist in the directory specified by alias
       alias /var/www/html/ops/;                       //Be sure to bring the "/" symbol after it
       rewrite ^/opp/hen.php(.*)$ /opp/hen.php?s=$1 last;
    # rewrite ^/opp/(.*)$ /opp/hen.php?s=$1 last;
       }

   location /wang {                    //The matching path directory wang must actually exist in the directory specified by root (there must be a wang directory under / var/www/html)
      root /var/www/html;
     }

 }

2. location matching order

Location instruction is one of the most critical instructions in nginx. The function of location instruction is to match different URI requests, and then do different processing and response to requests. Among them, it is difficult to understand the matching order of multiple locations

nginx has two layers of instructions to match the request URI.

Level 1: server Command, which passes the domain name ip And port to do the first level matching

Level 2: when a match is found server Enter here after server of location matching

The matching of location does not exactly follow the order in which it appears in the configuration file. The request URI will be matched according to the following rules:

  1. Accurate matching first  = , If the accurate matching is successful, other types of matching will be stopped immediately;
  2. Prefix matching is performed when no exact matching is successful. Find first with  ^~  Prefix match with  ^~  If the prefix matching of is successful, other types of matching will be stopped immediately, and ordinary prefix matching (without parameters  ^~ ) If successful, it will be temporarily saved and continue to find regular matches;
  3. =   and  ^~  On the premise that no match is successful, find the regular match  ~  and  ~* . When there are multiple regular matches at the same time, they will be matched first according to the order in which they appear in the configuration file. If they hit, other types of matching will be stopped immediately;
  4. If all regular matches are unsuccessful, the normal prefix match (without parameters) temporarily stored in step 2 is returned  ^~ ) result

A simple summary of the above rules is that the priority is from high to low (the smaller the serial number, the higher the priority):

1. location = # exact match
 2. location ^ ~ # with parameter prefix matching
 3. location ~ # regular matching (case sensitive)
4. location ~* # regular matching (case insensitive)
5. location /a # common prefix matching, with priority lower than prefix matching with parameters
 6. location / # any unsuccessful matching will be processed here

Case 1

server {
    server_name website.com;
    location /doc {
        return 701; # In this way, you can easily know where the request is
    }
    location ~* ^/document$ {
        return 702; 

    }
}

Test: match to 702, indicating that the regular matching priority of ~ * is higher than that of ordinary prefix matching

 

curl -I 192.168.40.132/document
HTTP/1.1 702 
Server: nginx/1.20.1
Date: Thu, 04 Nov 2021 03:13:20 GMT
Content-Length: 0
Connection: keep-alive

 

Case 2

server {
    server_name website.com;
    location = /document {
        return 701;
    }
    location ~* ^/document$ {
        return 702;
    }
}

 

Test results: exact matching is higher than regular matching

#curl -I 192.168.40.132/document
HTTP/1.1 701 
Server: nginx/1.20.1
Date: Thu, 04 Nov 2021 03:21:04 GMT
Content-Length: 0
Connection: keep-alive

Case 3

server {
    server_name website.com;
    location ^~ /doc {
        return 701;
    }
    location ~* ^/document$ {
        return 702;
    }
}

Test results:^~   Prefix matching with parameters is better than regular matching  ~* (first prefix matches)  ^~  Regular matches will not be searched after hitting, so the first hit will be made)

curl -I 192.168.40.132/document
HTTP/1.1 701 
Server: nginx/1.20.1
Date: Thu, 04 Nov 2021 03:23:59 GMT
Content-Length: 0
Connection: keep-alive

 

 

 

One article clarifies the location configuration in nginx (Series I) - Zhihu (zhihu.com)   There are many cases and the analysis is in place

Nginx virtual directory alias and root directory - all the glitz - blog Garden (cnblogs.com)

Detailed explanation and installation of the most complete Nginx configuration file - Zhihu (zhihu.com)

Added by vallette on Thu, 04 Nov 2021 08:00:54 +0200