“This is the 19th day of my participation in the Gwen Challenge.

Default configuration file


user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
	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  /var/log/nginx/access.log  main;

	sendfile        on;
	#tcp_nopush on;

	keepalive_timeout  65;

	#gzip on;

	#include /etc/nginx/conf.d/*.conf;server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; } error_page 500 502 503 504 404 /50x.html; location = /50x.html { root /usr/share/nginx/html; }}}Copy the code
  • User: sets the system user of the nginx service
  • Worker_processes: indicates the number of working processes
  • Error_log: error log of nginx
  • Pid: indicates the PID when the nginx service is started
  • Events:
    • Worker_connections: Maximum number of connections allowed per process
    • Use: indicates the number of working processes
  • server:
    • Listen 80 Listens to port 80 of server
    • Server_name Configurable domain name
    • Location /: Root directory
      • Root & index: the default access page
    • Error_page: error page, 500 502 503 504 404 These status codes will be redirected to /50x.html
    • Location = /50x.html: responds to access to 50x.html, 50x.html in the root directory
  • Keepalive_timeout: indicates the client timeout time
  • Include /etc/nginx/conf.d/*. Conf: includes configuration files. Generally, one configuration file contains one server

Log format log_format

#The default configuration
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
Copy the code

1.Http variables: arg_PARAMETER, http_HEADER, and sent_http_HEADER

​ eg:log_format main ‘
a r g P A R A M E T E R arg_PARAMETER
http_HEADER $sent_http_HEADER’

2. Built-in variables:

Built-in variables are stored in the ngx_HTTP_CORE_module module and are named the same way as Apache server variables. In summary, these variables represent the content of the client request header. Here are the built-in variables supported by Nginx:

$arg_name

The parameter name in the request, which is “?” Arg_name =arg_value arg_name

$args

Parameter values in the request

$binary_remote_addr

A binary client address, fixed in length of 4 bytes

$body_bytes_sent

The number of bytes transmitted to the client, not counting the response header; This variable remains compatible with the “%B” parameter in Apache’s mod_log_config module

$bytes_sent

Number of bytes transferred to the client (1.3.8, 1.2.5)

$connection

Serial numbers of TCP connections (1.3.8, 1.2.5)

$connection_requests

Current number of TCP connection requests (1.3.8, 1.2.5)

$content_length

Content-length Specifies the request header field

$content_type

Content-type Specifies the request header field

$cookie_name

The name of the cookie

$document_root

The document root or alias for the current request

$document_uri

With $uri

$host

The priorities are as follows: HOST name of the HTTP request line > HOST request header field > name of the server matching the request

$hostname

The host name

$http_name

Matches any request header field; The latter part of the variable name can be replaced with any request header field. For example, if you need to obtain the HTTP request header accept-language in the configuration file, replace “-” with underscores and uppercase letters with lowercase letters in the format of $http_accept_language.

**$https **

If SSL mode is enabled, the value is “on”; otherwise, it is an empty string.

$is_args

If there are parameters in the request, the value is “? “. Otherwise, an empty string.

$limit_rate

Used to set the speed limit for the response, see limit_rate.

$msec

Current Unix timestamps (1.3.9, 1.2.6)

$nginx_version

Nginx version

$pid

PID of worker process

$pipe

The value is “p” if the request is coming from a pipe communication, “otherwise.” (1.3.12 1.2.7)

$proxy_protocol_addr

Gets the client address for proxy access to the server, an empty string if it is direct access. (1.5.12)

$query_string

With $args

$realpath_root

The real path of the document root or alias currently requested will convert all symbolic links to the real path.

$remote_addr

Client address

$remote_port

Client port

$remote_user

User name used for the HTTP basic authentication service

$request

Represents the client’s request address

$request_body

Client request body

This variable can be used in location to pass the request body to the next level of proxy server via proxy_pass, fastCGI_pass, UWSGI_pass, and SCGI_pass.

$request_body_file

Save the client request body in a temporary file. After the file is processed, delete the file. Set client_body_IN_FILe_only if you want to enable this function. If you want to pass the file to the proxy server on the back end, you need to disable request body by setting proxy_pass_request_body off. Fastcgi_pass_request_body off, uwsgi_pass_request_body off, or scgi_pass_request_body off.

$request_completion

The value is “OK” if the request is successful, and null if the request is incomplete or not the last part of a scope request.

$request_filename

The file path of the current connection request, generated by the root or Alias directive and the URI request.

$request_length

The length of the request (including the address of the request, HTTP header, and request body) (1.3.12, 1.2.7)

$request_method

HTTP request method, usually “GET” or “POST”

$request_time

Time to process client request usage (1.3.9, 1.2.6); The timing begins with the first byte read from the client.

$request_uri

This variable is equal to the original URI containing some of the client request parameters. It cannot be changed. See $URI to change or rewrite the URI, excluding the host name, for example: “/ CNPHP /test.php? Arg = freemouse “.

$scheme

The Web protocol used for the request, “HTTP” or “HTTPS”

$sent_http_name

You can set any HTTP response header field; The last part of the variable name “Name” can be replaced with any response header field. To set the response header content-Length, replace “-” with underscores and uppercase letters with lowercase letters in the format of $SENT_HTTP_content_length 4096.

$server_addr

Note that: To avoid accessing the Linux kernel, set the IP address in the configuration file in advance.

$server_name

The server name is www.cnphp.info

$server_port

Server port

$server_protocol

HTTP version of the server, usually “HTTP/1.0” or “HTTP/1.1”

$status

HTTP Response codes (1.3.2, 1.2.2)


t c p i n f o r t t . tcpinfo_rtt,
tcpinfo_rttvar,
t c p i n f o s n d c w n d . tcpinfo_snd_cwnd,
tcpinfo_rcv_space

Details about the CLIENT TCP connection

$time_iso8601

Server time in ISO 8610 format (1.3.12, 1.2.7)

**
t i m e l o c a l time_local
arg_name **

The parameter name in the request, which is “?” Arg_name =arg_value arg_name

$args

Parameter values in the request

$binary_remote_addr

A binary client address, fixed in length of 4 bytes

$body_bytes_sent

The number of bytes transmitted to the client, not counting the response header; This variable remains compatible with the “%B” parameter in Apache’s mod_log_config module

$bytes_sent

Number of bytes transferred to the client (1.3.8, 1.2.5)

$connection

Serial numbers of TCP connections (1.3.8, 1.2.5)

$connection_requests

Current number of TCP connection requests (1.3.8, 1.2.5)

**$content_lengt **

Content-length Specifies the request header field

$content_type

Content-type Specifies the request header field

**$cookie_name **

The name of the cookie

$document_root

The document root or alias for the current request

$document_uri

With $uri

$host

The priorities are as follows: HOST name of the HTTP request line > HOST request header field > name of the server matching the request

$hostname

The host name

$http_name

Matches any request header field; The latter part of the variable name can be replaced with any request header field. For example, if you need to obtain the HTTP request header accept-language in the configuration file, replace “-” with underscores and uppercase letters with lowercase letters in the format of $http_accept_language.

$https

If SSL mode is enabled, the value is “on”; otherwise, it is an empty string.

$is_args

If there are parameters in the request, the value is “? “. Otherwise, an empty string.

$limit_rate

Used to set the speed limit for the response, see limit_rate.

$msec

Current Unix timestamps (1.3.9, 1.2.6)

$nginx_version

Nginx version

$pid

PID of worker process

$pipe

The value is “p” if the request is coming from a pipe communication, “otherwise.” (1.3.12 1.2.7)

$proxy_protocol_addr

Gets the client address for proxy access to the server, an empty string if it is direct access. (1.5.12)

$query_string

With $args

$realpath_root

The real path of the document root or alias currently requested will convert all symbolic links to the real path.

$remote_addr

Client address

$remote_port

Client port

$remote_user

User name used for the HTTP basic authentication service

$request

Represents the client’s request address

$request_body

Client request body

This variable can be used in location to pass the request body to the next level of proxy server via proxy_pass, fastCGI_pass, UWSGI_pass, and SCGI_pass.

$request_body_file

Save the client request body in a temporary file. After the file is processed, delete the file. Set client_body_IN_FILe_only if you want to enable this function. If you want to pass the file to the proxy server on the back end, you need to disable request body by setting proxy_pass_request_body off. Fastcgi_pass_request_body off, uwsgi_pass_request_body off, or scgi_pass_request_body off.

$request_completion

The value is “OK” if the request is successful, and null if the request is incomplete or not the last part of a scope request.

$request_filename

The file path of the current connection request, generated by the root or Alias directive and the URI request.

$request_length

The length of the request (including the address of the request, HTTP header, and request body) (1.3.12, 1.2.7)

$request_method

HTTP request method, usually “GET” or “POST”

$request_time

Time to process client request usage (1.3.9, 1.2.6); The timing begins with the first byte read from the client.

$request_uri

This variable is equal to the original URI containing some of the client request parameters. It cannot be changed. See $URI to change or rewrite the URI, excluding the host name, for example: “/ CNPHP /test.php? Arg = freemouse “.

$scheme

The Web protocol used for the request, “HTTP” or “HTTPS”

$sent_http_name

You can set any HTTP response header field; The last part of the variable name “Name” can be replaced with any response header field. To set the response header content-Length, replace “-” with underscores and uppercase letters with lowercase letters in the format of $SENT_HTTP_content_length 4096.

$server_addr

Note that: To avoid accessing the Linux kernel, set the IP address in the configuration file in advance.

$server_name

The server name is www.baidu.com

$server_port

Server port

$server_protocol

HTTP version of the server, usually “HTTP/1.0” or “HTTP/1.1”

$status

HTTP Response codes (1.3.2, 1.2.2)

* *, * * tcpinfortt ∗ ∗, tcpinfo_rtt tcpinfortt ∗ ∗, tcpinfo_rttvar, tcpinfosndcwnd, tcpinfo_snd_cwnd, tcpinfosndcwnd,tcpinfo_rcv_space

Details about the CLIENT TCP connection

$time_iso8601

Server time in ISO 8610 format (1.3.12, 1.2.7)

$time_local

Server Time (LOG Format) (1.3.12, 1.2.7)

$uri

The current URI in the request (no request parameters, args) can be different from the browser-passed ARgs), can be different from the browser-passed value of request_URI, which can be modified by internal redirection or using the index directive, $uri does not contain a host name, such as “/foo/bar.html”.

Server Time (LOG Format) (1.3.12, 1.2.7)

$uri

The current URI in the request (no request parameters, args) can be different from the browser-passed ARgs), can be different from the browser-passed value of request_URI, which can be modified by internal redirection or using the index directive, $uri does not contain a host name, such as “/foo/bar.html”.

Monitor module http_stub_status_modules

Function: Monitors Nginx client status

Scope: server; location

Check the configuration parameter root @ 3 de922dd7a75: / usr/share/nginx/html# nginx -v nginx version: Nginx /1.19.0 built by GCC 8.3.0 (Debian 8.3.0-6) built with OpenSSL 1.1.1d 10 Sep 2019 TLS SNI support Enabled configure  arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-g -O2 - fdebug - prefix - map = / data/builder/debuild/nginx - 1.19.0 / debian/debuild - base/nginx - 1.19.0 = - fstack - protector - strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie'Copy the code
  1. Configuration syntax: Configure on a server
location  /status {
	stub_status;
}
Copy the code
  1. After the modification, test the configuration file for errors
root@3de922dd7a75:/etc/nginx# nginx -tc ./nginx.conf 
nginx: the configuration file /etc/nginx/./nginx.conf syntax is ok
nginx: configuration file /etc/nginx/./nginx.conf test is successful
Copy the code
  1. Reloading configuration files
root@3de922dd7a75:/etc/nginx# nginx	-s reload /etc/nginx/nginx.conf
Copy the code
  1. Visit HTTTP :// IP /stasus again
Active connections: 2 
server accepts handled requests
 4 4 1 
Reading: 0 Writing: 1 Waiting: 1 
Copy the code
  1. Nginx_status,
Active connections: 4 ##server accepts handled requests ## Server accepts nginx's configuration ## How many requests have been handled because it's been handled 0 ##Reading Nginx Reading client headers ##Writing Nginx returning client headers ##Waiting Waiting = active - (Reading+Writing) with keep-alive enabledCopy the code

Module http_random_index_module

Effect: Select a random home page in the home directory

Default: Disable

Scope: location

  1. Configuration syntax: Configure in location
location / {
	root /etc/nginx/html;
	random_index on;
}
Copy the code
  1. Create a new HTML file in /etc/nginx/html
  2. Repeat the previous section to check the configuration file, reload the configuration file, visit in the browser, keep refreshing, different pages appear

The default module is http_sub_module

Function: HTTP content replacement

Common options: sub_filter string replacement; Sub_filter_last_modified on | off; sub_filter_once on|off

Scope: HTTP; Server; location

  1. The configuration syntax

    location / { root /etc/nginx/html; index index.html index.htm; sub_filter 'nginx' 'NGINX'; Nginx sub_filter_once off; # after closing, all nginx will be replaced}Copy the code

Nginx request access restrictions

Request limits

  1. Connection frequency limit: limit_conn_module

    Limit_conn_zone Key zone=name:size, scope: HTTP

    Limit_conn Zone number, scope: HTTP, server, location

  2. Request frequency limit: limit_req_module

    limit_req_zone key zone=name:size rate=rate,http

    Limit_req zone=name, scope: HTTP, server, location

  3. Configuration syntax:

    In HTTP mode, the IP address of the client is used as the key, the key is restricted, and a 1 MBIT/s space is required for storing access frequency information. $binary_remote_addr Saves zone space. Rate =1r/s: indicates the access frequency of clients with the same id. The value is limited to one request per second, that is, one request per second.

   limit_conn_zone $binary_remote_addr zone=conn_zone:1m
   limit_req_zone $binary_remote_addr zone=req_zone:1m rate=1r/s
Copy the code
  1. Configure localtion:
location  /status {
   root html;
   #   limit_conn conn_zone 1;  Allow only one connection at a time
   #   limit_req zone=req_zone burst=3 nodelay;  
   #   limit_req zone=req_zone burst=3;
   #   limit_req zone=req_zone;
   index show.html;
}
Copy the code

Limit_req zone=req_zon: Processes data at the rate set

Burst =3: Set a buffer size of 3. When a large number of requests (bursts) come in, requests exceeding the frequency limit can be placed in this buffer to wait. However, there are only 3 places in this buffer.

Nodelay: If set, it provides the ability to process (burst + rate) requests at once, and returns 503 when the number of requests exceeds (**burst + rate). If it is not set, all requests are queued in turn

Access restrictions

Ip-based access control: http_access_module

  1. Common options:

    Allow the address | CIDR | Unix: | all. Scope: HTTP, server, location, limit_except

    Allow Allows access. Set address to an IP address

    Deny the address | CIDR | Unix: | all. Scope: HTTP, server, location, limit_except

    Deny Deny access. Set address to an IP address

  2. Configure under location:

    location / {
    	root html;
        deny 192.168.1.74;#也可以配置IP段:192.168.1.0/24
        allow all;
        index show.html;
    }
    Copy the code

    As shown above, the ‘/’ directory under location is not accessible to users whose IP address is 192.168.1.74. All other IP addresses are accessible. When 192.168.1.74 is accessed, page 403 appears and access is not allowed.

  3. Limitations:

    Since the http_access_module access control is restricted to the client’S IP address, all connections to and from nginx are treated as clients. This IP control is disabled when there is a proxy service between the real client and Nginx.

  1. Summary of limited solutions:

    Method 1: use HTTP header information to control access, such as HTTP_X_FORWARD_FOR Method 2: combine geo module method 3: pass through HTTP custom variables

    The http_X_forwarded_for header is a better way to solve this problem by requiring access to all of the used IP addresses

http_x_forwarded_for = Client IP, Proxy(1)IP, Proxy(2)IP,...
Copy the code

User-based trust login: http_auth_basic_module

  1. Common options:

    Auth_basic string | off. Default: auth_basic off. Scope: HTTP, server, location, limit_except

    Auth_basic_user_file file. Scope: HTTP, server, location, limit_except

  2. Configuration:

[root@msr-server ~]# yum install httpd-tools [root@msr-server conf.d]# htpasswd -c./auth_conf MSR New password: re-type New password: Adding password for user MSR [root@msr-server conf.d]# ll # Check total 8-rw-r --r-- 1 root root 42 Jun 19 14:05 auth_conf -rw-r--r-- 1 root root 1144 Jun 16 18:09 default.conf [root@msr-server conf.d]# more auth_conf # msr:$apr1$ripuvDcJ$274OgHXOPwCb5kJ5dggq7.Copy the code
  1. Configure it under Location
location / { root html; auth_basic "AUth access!" ; auth_basic_user_file /etc/nginx/conf.d/auth_conf; index show.html; }Copy the code

If you visit it again, the authentication box will appear. Although access control can be achieved, but user information depends on external files, operation management machinery, low efficiency. So you can combine Nginx with LUA to achieve efficient authentication, Nginx and LDAR are the same, using the Nginx-Auth-LDAR module