Nginx Core Configuration Details

Keywords: Linux Nginx Mobile curl PHP

1 Global Configuration

user nginx nginx; # Users and groups that initiate the nginx worker process, defaulting to nobody
worker_processes auto; # Number of nginx worker processes started, default 1
worker_cpu_affinity 0001 0010 0100 1000; #Binding Nginx_as a process to the specified CPU core, the default Nginx is not to bind to the process. Binding does not mean that the current nginx process is exclusive to the core CPU, but it guarantees that the process will not run on other cores, which greatly reduces the number of jumps of nginx as a process on different CPU cores, reducing resource allocation and recycling by the CPU to the process, andMemory management, etc., can effectively improve the performance of the nginx server, or can be set to auto.
//You can execute the following commands to see if the worker processes are running consistently on the same core CPU
[root@CentOS7-01 ~]#watch -n1 'ps axo pid,cmd,psr,user | grep nginx|grep -v grep'
#Error_Logging configuration, syntax: error_log file [debug | info | notice | warn | error | crit | alert | emerg]
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
error_log  logs/error.log  error;

pid /run/nginx.pid; # pid File Save Path
worker_priority 0; # Worker process nice value, -20~19
worker_rlimit_nofile 65536; #This number includes all connections to Nginx (e.g., connections to proxy servers, etc.), Not only client connections, but also the actual number of concurrent connections cannot exceed the maximum number of open connections at the system level.
daemon off; #Front Desk Transport Nginx Services In test, docker, and other environments.
master_process off|on; #Whether to turn on the master-woker_mode of Nginx is only available for development debugging scenarios.
events { #Event Model Configuration Parameters
worker_connections 65536; #Set the maximum number of concurrent connections for a single process
use epoll; #For epoll event-driven, Nginx_holds a large number of event-driven, such as select, poll, epoll, can only be set in the events module.
accept_mutex on; #Optimize settings where there are only requests at the same time to prevent multiple sleep processes from waking up at the same time. on is to prevent from waking up at the same time. Default is off. The process of waking up all becomes a shock'. Therefore, nginx should be optimized appropriately just after installation.
multi_accept on; #Each process of the Nginx server can accept multiple new network connections at the same time, but it needs to be configured in the configuration file. This command is turned off by default, that is, the default is to accept only one new network connection by default. When opened, multiple connections can be accepted at the same time.

2 http detailed configuration

http {
    include       mime.types; #Import Supported File Types
    default_type  application/octet-stream; #Set default type, prompt to download mismatched type files
#Log Configuration Section
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;
#Custom optimization parameters
    sendfile        on; #Implement zero copy of file
    #tcp_nopush     on; #sendfile is enabled and sent uniformly to clients after merging requests
    #tcp_nodelay off; #Whether the TCP_NODELAY option is enabled for a connection with keepalived mode turned on. When off, it delays sending by 0.2s, defaults to on, and does not delay sending, that is, it sends user response message.     
    #keepalive_timeout  0;
    keepalive_timeout  65; #Set Session Hold Time
    #gzip  on; #Turn on file compression

    server {
        listen       80; #Set listening address and port
        server_name  localhost; #Set server name to write multiple spaces separated and support regular expressions

        #charset koi8-r; #Set encoding format, default is Russian format, can be changed to utf-8

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html; #Define error page
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1; #Forward php requests to the specified web server in http_
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000; #Forward php requests to php processing in fastcgi_mode
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht { #Deny web access to specified files, such as many stations that change the redirection of files through.htaccess files.
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server { #_Define virtual server
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm; #Specifies the default file, which is provided by the ngx_http_index_module module
    #    }
    #}

    # HTTPS server
    #
    #server { #https server configuration
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

3 Core Configuration Example

Virtual hosts that perform different functions based on different IP, ports, and domain names rely on the core module ngx_http_core_module implementation.

3.1 Create a new PC web site

[root@CentOS7-01 ~]#mkdir /apps/nginx/conf/vhosts
[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location / {
    root html/pc;
  }
}
[root@CentOS7-01 ~]#mkdir /apps/nginx/html/pc
[root@CentOS7-01 ~]#echo "pc web" > /apps/nginx/html/pc/index.html
[root@CentOS7-01 ~]#vim /apps/nginx/conf/nginx.conf
include /apps/nginx/conf/vhosts/*.conf; #Add to http block
[root@CentOS7-01 ~]#sed -i '1s/$/ pc.hechunping.tech/' /etc/hosts

//Access Test
[root@CentOS7-01 ~]#curl -i pc.hechunping.tech
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Thu, 02 Jan 2020 12:07:55 GMT
Content-Type: text/html
Content-Length: 7
Last-Modified: Thu, 02 Jan 2020 11:32:27 GMT
Connection: keep-alive
ETag: "5e0dd4cb-7"
Accept-Ranges: bytes

pc web

3.2 Create a new Mobile web site

[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/mobile.conf 
server {
  listen 80;
  server_name mobile.hechunping.tech;
  location / {
    root html/mobile;
  }
}
[root@CentOS7-01 ~]#mkdir /apps/nginx/html/mobile
[root@CentOS7-01 ~]#echo "mobile web" > /apps/nginx/html/mobile/index.html
[root@CentOS7-01 ~]#sed -i '1s/$/ mobile.hechunping.tech/' /etc/hosts
[root@CentOS7-01 ~]#systemctl reload nginx

//Access Test
[root@CentOS7-01 ~]#curl -i mobile.hechunping.tech/index.html
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Thu, 02 Jan 2020 12:05:26 GMT
Content-Type: text/html
Content-Length: 11
Last-Modified: Thu, 02 Jan 2020 12:04:43 GMT
Connection: keep-alive
ETag: "5e0ddc5b-b"
Accept-Ranges: bytes

mobile web

3.3 root and alias

3.3.1 root: Specify the home directory of the web. When locations are defined, the absolute path of a file is equal to root+location, for example:

[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location / {
    root html/pc;
  }
  location /about {
    root html/pc; #In the pc directory, you must have about, otherwise you will get a 404 error when accessing
  }
}
[root@CentOS7-01 ~]#mkdir /apps/nginx/html/pc/about
[root@CentOS7-01 ~]#echo "about page ..." > /apps/nginx/html/pc/about/index.html

//Access Test
[root@CentOS7-01 ~]#curl -i pc.hechunping.tech/about/index.html
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Thu, 02 Jan 2020 12:28:07 GMT
Content-Type: text/html
Content-Length: 15
Last-Modified: Thu, 02 Jan 2020 12:25:03 GMT
Connection: keep-alive
ETag: "5e0de11f-f"
Accept-Ranges: bytes

about page ...

3.3.2 alias: Defining a path alias will redefine the path visited to its specified path, such as:

[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location / {
    root html/pc;
  }
  location /alpc { #If'/'is added, then'/' must be added to the path configuration of alias, otherwise access error will occur
    alias html/pc; #When accessing alpc, the contents of alias-defined/apps/nginx/html/pc_are displayed.
  }
}

//Access Test
[root@CentOS7-01 ~]#systemctl reload nginx
[root@CentOS7-01 ~]#cat /apps/nginx/html/pc/index.html 
pc web
[root@CentOS7-01 ~]#curl -i pc.hechunping.tech/alpc/index.html
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Thu, 02 Jan 2020 13:07:30 GMT
Content-Type: text/html
Content-Length: 7
Last-Modified: Thu, 02 Jan 2020 11:32:27 GMT
Connection: keep-alive
ETag: "5e0dd4cb-7"
Accept-Ranges: bytes

pc web

3.3.3 Differences between the two

1) The directory alias specifies is accurate, that is, the files in the path directory where the location matches the access are found directly in the path directory specified by alias, and the name of the path directory where the location matches the access can be arbitrarily specified, which is similar to the soft-connect function of the Linux file system;
2) In the alias virtual configuration directory, if'/'is added after the location matching path directory, then'/' must also be added after the alias specified directory, otherwise 403
 3) The directory specified by root is the parent directory of the path directory matched by the location, and this path directory must be a subdirectory that actually exists in the root specified directory.
4) In the root directory configuration, access will not be affected if the location matches the path directory followed by no'/'.

Detailed use of 3.4 location

Syntax Rule: location [=|~|*|^~]/uri/ {...}
= Before a standard uri, the request string needs to match the URI exactly, and if the match succeeds, stop matching downwards and process the request.
~ # Before the standard uri, the table contains regular expressions and distinguishes between write and match
 !~Before the standard uri, the table contains regular expressions and distinguishes between write and mismatch
 ~* 122;Before the standard uri, table contains regular expressions and is not write-sensitive and matches
 !~* Before the standard uri, the table contains regular expressions and is not write-sensitive and does not match
 Before the standard uri, the table contains regular expressions and what does the match start with
 $# Before the standard uri, table contains regular expressions and what does the match end with
   # Before the standard uri, the table_contains regular expressions and escape characters.Can I turn. *?
* 122;#Before the standard uri, table_contains regular expressions and represents any character of any degree

3.4.1 Exact Match

stay server Partial use location Configure one web Interface, Requirements: When accessing nginx Display the specified resource on the server html Content of the file
[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location /test.html {
    root /apps/nginx/html/mobile;
  }

  location = /test.html {
    root /apps/nginx/html/pc;
  }
}
[root@CentOS7-01 ~]#cat /apps/nginx/html/mobile/test.html 
mobile location
[root@CentOS7-01 ~]#cat /apps/nginx/html/pc/test.html 
pc location
[root@CentOS7-01 ~]#systemctl reload nginx
[root@CentOS7-01 ~]#curl pc.hechunping.tech/test.html
pc location

//From the test results above, you can see that the exact match is returned

3.4.2 Case sensitive matching

Match in lowercase only html End File
[root@CentOS7-01 mobile]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location ~ \.html$ {
    root /apps/nginx/html/mobile;
  }
}
[root@CentOS7-01 mobile]#ls /apps/nginx/html/mobile/test.*
/apps/nginx/html/mobile/test.html  /apps/nginx/html/mobile/test.Html
[root@CentOS7-01 mobile]#curl --head pc.hechunping.tech/test.html
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 03 Jan 2020 13:37:42 GMT
Content-Type: text/html
Content-Length: 16
Last-Modified: Fri, 03 Jan 2020 12:53:04 GMT
Connection: keep-alive
ETag: "5e0f3930-10"
Accept-Ranges: bytes

[root@CentOS7-01 mobile]#curl --head pc.hechunping.tech/test.Html
HTTP/1.1 404 Not Found
Server: nginx
Date: Fri, 03 Jan 2020 13:37:52 GMT
Content-Type: text/html
Content-Length: 146
Connection: keep-alive

3.4.3 Case insensitive matching

This pattern is case-sensitive html Files at the end are matched, case can be mixed, and this pattern is usually used to match static resources requested by the user and proceed to the next step
[root@CentOS7-01 mobile]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location ~* \.html$ {
    root /apps/nginx/html/mobile;
  }
}
[root@CentOS7-01 mobile]#systemctl reload nginx
[root@CentOS7-01 mobile]#ls /apps/nginx/html/mobile/test.*
/apps/nginx/html/mobile/test.html  /apps/nginx/html/mobile/test.Html
[root@CentOS7-01 mobile]#curl --head pc.hechunping.tech/test.html
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 03 Jan 2020 13:44:08 GMT
Content-Type: text/html
Content-Length: 16
Last-Modified: Fri, 03 Jan 2020 12:53:04 GMT
Connection: keep-alive
ETag: "5e0f3930-10"
Accept-Ranges: bytes

[root@CentOS7-01 mobile]#curl --head pc.hechunping.tech/test.Html
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 03 Jan 2020 13:44:14 GMT
Content-Type: text/html
Content-Length: 4
Last-Modified: Fri, 03 Jan 2020 13:27:17 GMT
Connection: keep-alive
ETag: "5e0f4135-4"
Accept-Ranges: bytes

3.4.4 Match starting with a URI

Match only to abc initial uri The content below will end the search and will no longer match uri Include abc Content under corresponding directory
[root@CentOS7-01 mobile]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location ^~ /abc {
    root /apps/nginx/html/mobile;
  }
  location /babc {
    root /apps/nginx/html/mobile;
  }
}
[root@CentOS7-01 mobile]#cat /apps/nginx/html/mobile/abc/index.html 
abc page
[root@CentOS7-01 mobile]#cat /apps/nginx/html/mobile/babc/index.html 
babc page
[root@CentOS7-01 mobile]#systemctl reload  nginx
[root@CentOS7-01 mobile]#curl  pc.hechunping.tech/abc/
abc page

3.4.5 Case insensitive matching of files ending with a file name

[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location ~* \.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|wmf|js)$ {
    root /apps/nginx/html/image;
  }
}
[root@CentOS7-01 ~]#ls /apps/nginx/html/image/
1.jpg  2.jpg  3.png  4.jpEg  Ab.jS  timg.jpg
[root@CentOS7-01 ~]#curl -I pc.hechunping.tech/4.jpEg
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 03 Jan 2020 14:11:07 GMT
Content-Type: image/jpeg
Content-Length: 16228
Last-Modified: Fri, 03 Jan 2020 14:03:22 GMT
Connection: keep-alive
ETag: "5e0f49aa-3f64"
Accept-Ranges: bytes

[root@CentOS7-01 ~]#curl -I pc.hechunping.tech/Ab.jS
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 03 Jan 2020 14:11:18 GMT
Content-Type: application/javascript
Content-Length: 16228
Last-Modified: Fri, 03 Jan 2020 14:10:19 GMT
Connection: keep-alive
ETag: "5e0f4b4b-3f64"
Accept-Ranges: bytes

[root@CentOS7-01 ~]#curl -I pc.hechunping.tech/3.png
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 03 Jan 2020 14:11:34 GMT
Content-Type: image/png
Content-Length: 16228
Last-Modified: Fri, 03 Jan 2020 14:03:11 GMT
Connection: keep-alive
ETag: "5e0f499f-3f64"
Accept-Ranges: bytes

3.4.6 Priorities

Matching priority: =, ^~, ~/~*, /
Location priority: (location =) > (location full path) > (location ^~path) > (location ~, ~* regular order) > (location part start path) > (/)

3.4.7 Production Use Cases

Direct matching Station roots speed up Nginx access processing:
location = / {
......;
}
location / {
......;
}
Static resource configuration:
location ^~ /static/ {
......;
}
#or
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
......;
}
Polygonal Configuration
location ~* /app1 {
    ......;
}
location ~* /app2 {
......;
}

3.5 nginx four-tier access control

Module-based access control ngx_http_access_module Implemented by matching client sources IP Address entry limit, 192 allowed here.168.7.72 this ip Visit
[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location /pc {
    root /apps/nginx/html;
    allow 192.168.7.72;
    deny all;
  }
}
//Access test, 192.168.7.72 is the address of another Linux server, tested here on this Linux server and on the physical machine
Linux The server
[root@CentOS7-02 ~]#ifconfig eth0 | awk -F"[ ]+" 'NR==2{print $3}'
192.168.7.72
[root@CentOS7-02 ~]#curl -i pc.hechunping.tech/pc/
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 04 Jan 2020 01:45:18 GMT
Content-Type: text/html
Content-Length: 7
Last-Modified: Thu, 02 Jan 2020 11:32:27 GMT
Connection: keep-alive
ETag: "5e0dd4cb-7"
Accept-Ranges: bytes

pc web

//Physical Machine
//403 status codes can be found in the access log
[root@CentOS7-01 ~]#tail -n1 -f /apps/nginx/logs/access.log 
192.168.7.1 - - [04/Jan/2020:09:46:12 +0800] "GET /pc/ HTTP/1.1" 403 548 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"

3.6 nginx Account Authentication Function

1)There are two ways to generate a password file
//Method 1: Use htpasswd command to generate, need to install httpd-tools package
[root@CentOS7-01 ~]#yum -y install httpd-tools
[root@CentOS7-01 ~]#htpasswd -cb /apps/nginx/conf/.passwd user1 123456 #The -c parameter is required only when the first user is created and not later when a new user is created, otherwise the previously created username password will be overwritten.
Adding password for user user1
[root@CentOS7-01 ~]#htpasswd -b /apps/nginx/conf/.passwd user2 123456
Adding password for user user2
[root@CentOS7-01 ~]#cat /apps/nginx/conf/.passwd 
user1:$apr1$/4bSUD79$AUHF6.EYkLwW6pvtinl/N1
user2:$apr1$F1c./Mk9$k3LBFsZ.EFaTSU6PdMk5r1
//Method 2: Generate using the openssl command
[root@CentOS7-01 ~]#printf "user1:$(openssl passwd -crypt 123456)\n" > /apps/nginx/conf/.passwd
[root@CentOS7-01 ~]#printf "user2:$(openssl passwd -crypt 123456)\n" >> /apps/nginx/conf/.passwd #Use append when creating the second user, otherwise the user name password created earlier will be overwritten.
[root@CentOS7-01 ~]#cat /apps/nginx/conf/.passwd 
user1:/p2JrkKzl2VvY
user2:.yQfiUOWOMJJE
2)To configure nginx configuration file
[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location /pc {
    root /apps/nginx/html;
    auth_basic "login password";
    auth_basic_user_file /apps/nginx/conf/.passwd;
  }
}
[root@CentOS7-01 ~]#systemctl reload nginx
3)Access Test
//If access is successful on the physical machine, remote user information can be obtained in nginx's access log as follows
[root@CentOS7-01 ~]#tail -n1 -f /apps/nginx/logs/access.log 
192.168.7.1 - user1 [04/Jan/2020:10:20:21 +0800] "GET /pc/ HTTP/1.1" 200 7 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"

3.7 Custom Error Page

When we visit a page that does not exist, the browser page usually reports a large 404 Not Found,This seems obviously unfriendly, so you can define 404 errors as your own by customizing the error page
[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  error_page 404 /error.html;
  location = /error.html {
    root html;
  }
}
[root@CentOS7-01 ~]#echo "The page you visited is missing ~~" >/apps/nginx/html/error.html
[root@CentOS7-01 ~]#systemctl reload nginx

//Access Test

3.8 Custom Access Log

By default, the path to log storage is nginx Installation Path logs Catalog, but we can separate the logs of individual businesses to make statistics and management easier
[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  error_page 404 /error.html;
  access_log /data/nginx/logs/pc.hechunping.tech/access.log;
  error_log /data/nginx/logs/pc.hechunping.tech/error.log;
  location = /error.html {
    root html;
  }
}
[root@CentOS7-01 ~]#systemctl reload nginx
[root@CentOS7-01 ~]#ls /data/nginx/logs/pc.hechunping.tech/
access.log  error.log

3.9 Detect file existence

try_files Will check the existence of the pieces in order, return to the #1 found or folder (appended at the end)"/"Table is a folder. If all folders or folders are not found, they will be redirected to the last parameter.Only the last parameter can cause internal redirection, the previous parameter only sets the internal URI Direction.The last parameter is fallback URI And must exist, otherwise an internal 500 error will occur.

[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location /pc {
    root html;
    try_files $uri $uri/index.html $uri.html /pc/defautl.html;
  }
}
[root@CentOS7-01 ~]#cat /apps/nginx/html/pc/defautl.html 
pc default page ...
[root@CentOS7-01 ~]#systemctl reload nginx

//Access Test
//When the resource accessed does not match all the uri preceding it, the contents of the defautl.html page are displayed, as shown below

You can also customize the last parameter as a status code, as shown below

3.10 Long Connection Matching

keepalive_timeout number; #Set keep connection timeout, 0 tables disable connection, default is 75s, usually configured in http field as site global configuration 
keepalive_requests number; #Maximum number of resource requests allowed on connections, default to 100

keepalive_timeout 65 65; #When a connection is opened, the session holding time for returning to the client is 65s, and the cumulative requests for a single connection are disconnected after a specified number of requests or 65 seconds. After that, 65 means the time-out time displayed in the response header sent to the client is set to 65s: If the client is not set, the time-out time will not be displayed.

//Access Test
[root@CentOS7-01 ~]#curl -I pc.hechunping.tech/pc
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 04 Jan 2020 07:43:31 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 7
Last-Modified: Thu, 02 Jan 2020 11:32:27 GMT
Connection: keep-alive
Keep-Alive: timeout=65
ETag: "5e0dd4cb-7"
Accept-Ranges: bytes

//If set to Table 0_Turn off session retention, as shown below
curl -I pc.hechunping.tech/pc
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 04 Jan 2020 07:45:23 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 7
Last-Modified: Thu, 02 Jan 2020 11:32:27 GMT
Connection: close
ETag: "5e0dd4cb-7"
Accept-Ranges: bytes

keepalive_requests 2; #The maximum number of resource requests allowed on a long connection, set here to 2, will close the long connection when reached twice.

//Access Test
# Testing with telnet commands
[root@CentOS7-01 ~]#telnet pc.hechunping.tech 80
Trying 127.0.0.1...
Connected to pc.hechunping.tech.
Escape character is '^]'.
GET /pc/index.html HTTP/1.1
HOST: pc.hechunping.tech

# Response Header Information
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 04 Jan 2020 07:48:50 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 7
Last-Modified: Thu, 02 Jan 2020 11:32:27 GMT
Connection: keep-alive
Keep-Alive: timeout=65
ETag: "5e0dd4cb-7"
Accept-Ranges: bytes

# Page Content
pc web
GET /pc/index.html HTTP/1.1
HOST: pc.hechunping.tech

# Response Header Information
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 04 Jan 2020 07:49:01 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 7
Last-Modified: Thu, 02 Jan 2020 11:32:27 GMT
Connection: close
ETag: "5e0dd4cb-7"
Accept-Ranges: bytes
# Page Content
pc web
Connection closed by foreign host. #This long connection is closed after two requests for resources

3.11 Configure nginx as the download server

[root@CentOS7-01 download]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location /download { 
    autoindex on;
    autoindex_exact_size on;
    autoindex_localtime on;
    limit_rate 20k;
    root html/pc;
  }
}
[root@CentOS7-01 download]#ls /apps/nginx/html/pc/download/ #There cannot be an index.html file in this directory
README.md  ubuntu-18.04.3-server-amd64.iso
[root@CentOS7-01 download]#systemctl reload nginx

//Access tests, as shown below


3.12 Configure nginx as the upload server

client_max_body_size 1m; #Set the maximum value that allows clients to upload a single item, default value is 1m
client_body_buffer_size size; #_Buffer that receives the body part of each client request message; default 16k; beyond which it will be temporarily stored to a location on the disk defined by the client_body_temp_path directive below
client_body_temp_path path [level1 [level2 [level3]]]; #Sets the temporary storage path and the structure and number of records for the body part of the storage client requests report, records a number named 16 digits, so that the values after hash truncate 1, 2, and 2 digits from back to front as the file names

1 Level_records take up one hexadecimal digit, that is, 2^4=16 Record 0-f
2 Level_records take up 2 bits of hexadecimal, that is, 2^8=256 Ge Fang 00-ff
3 Level_records take up 2 bits of hexadecimal, that is, 2^8=256 Ge Fang 00-ff

//Configuration example:
client_max_body_size 10m;
client_body_buffer_size 16k;
client_body_temp_path /data/nginx/temp 1 2 2; #reload Nginx will actively create temp_records

3.13 Other Configurations

3.13.1 Which browser to disable connections

keepalive_disable none | browser ...;
For example, disable the ie6 browser and add the following parameters to the configuration file to configure it in http,server,location blocks
keepalive_disable msie6;

3.13.2 Restricts the client to use only the specified request method, only in the location block

limit_except method ... { ... } ;

method:GET,HEAD,POST,PUT,DELETE,MKCOL,COPY,MOVE,OPTIONS,PROPFIND,PROPPATCH,LOCK,UNLOCK,PATCH
# Restrictions allow only clients of 192.168.7.0 network segment to use specified GET and HEAD methods
[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location /pc {
    root html;
    limit_except GET {
      allow 192.168.7.0/24;
      deny all;
    }
  }
}
[root@CentOS7-01 ~]#systemctl reload nginx
[root@CentOS7-01 ~]#curl -XPUT /etc/issue pc.hechunping.tech/pc
curl: (3) <url> malformed
<html>
<head><title>403 Forbidden</title></head> #nginx refuses to upload
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>

# Comment out the configuration that limits the specified method
[root@CentOS7-01 ~]#cat /apps/nginx/conf/vhosts/pc.conf 
server {
  listen 80;
  server_name pc.hechunping.tech;
  location /pc {
    root html;
    #limit_except GET {
    #  allow 192.168.7.0/24;
    #  deny all;
    #}
  }
}
[root@CentOS7-01 ~]#systemctl reload nginx
[root@CentOS7-01 ~]#curl -XPUT /etc/issue pc.hechunping.tech/pc
curl: (3) <url> malformed
<html>
<head><title>405 Not Allowed</title></head> #nginx is allowed, but the program does not support uploading
<body>
<center><h1>405 Not Allowed</h1></center>
<hr><center>nginx</center>
</body>
</html>

3.13.3 Whether_asynchronous file I/O(AIO) functionality is enabled requires compilation to be enabled

The linux 2.6+ kernel provides the following system tuning to hold aio:
1. SYS_io_setup: context of aio
 2. SYS_io_submit: Submit I/O operation request
 3. SYS_io_getevents: Get completed I/O events
 4. SYS_io_cancel: Cancel I/O operation request
 5. SYS_io_destroy: Destroy the context of aio

3.13.4 Enable direct I/O

directio size | off; #Operations are exactly the opposite of aio, AIO is to read directio is to write direct I/O to disk, turn on direct I/O, and turn off by default. When is equal to a given such as directio 4m, write to disk synchronously (directly), write to cache.

3.13.5 Whether to cache open file information

open_file_cache off; #Whether to cache opened messages
open_file_cache max=N [inactive=time];
nginx You can cache three kinds of information:
1) Metadata: Descriptor of the file, modification time of the file and latest changes
2) Open Recording Structure
3) Information about items not found or not authorized to access
max=N: Maximum number of cacheable cache entries; when the maximum is reached, it causes_ LRU(Least recently used,Least recent)Algorithmic Implementation Management
inactive=time: When cached item is active, the number of misses or hits specified here is less than
open_file_cache_min_uses The cached item for the number of times specified by the directive is the active item and will be deleted

Within the time specified by the inactive parameter of the 3.13.6 open_file_cache directive, fewer hits specified here_can be classified as active items

open_file_cache_min_uses number; #Default value is 1

3.13.7 Whether or not to cache information of the wrong class when looking up

open_file_cache_errors on | off; #The default value is off

Frequency of validation checks for 3.13.8 cache entries

open_file_cache_valid time; #Default value is 60s
open_file_cache max=10000 inactive=60s; #Maximum 10,000 caches, active data timeout 60s
open_file_cache_valid 60s;  #Check cache data validity at 60 seconds interval
open_file_cache_min_uses 5; #Less than five hits in 60 seconds before being marked as active
open_file_cache_errors on;  #Cache error information

3.13.9 Hide the Nginx server version.

server_tokens off; #defaults to on

Access Test
 Result at default value
[root@CentOS7-01 ~]#curl -I pc.hechunping.tech
HTTP/1.1 200 OK
Server: nginx/1.16.1
...

The result set to off, added to the global configuration in the http block
[root@CentOS7-01 ~]#curl -I pc.hechunping.tech
HTTP/1.1 200 OK
Server: nginx
...

Posted by soldbychris on Sun, 05 Jan 2020 05:47:49 -0800