Nginx Advanced Configuration

Nginx Advanced Configuration

1. Nginx status page

nginx module ngx_http_auth_basic_module achieve, you need to add the compiler parameters when compiling the installation of nginx -with-http_stub_status_module, or after the completion of the monitoring will be prompted to configure syntax errors based.

Basic status information of the status page for outputting nginx

location /nginx_status {
    stub_status;
    allow 192.168.0.0/16;
    allow 127.0.0.1;
    deny all;
}

mark

Active connections: currently active client connections, including connections waiting for free connections.
accepts: GDP statistics, the total number since the start of the Nginx has accepted the client request.
handled: GDP statistics, since the start of the Nginx has completed processing the total number of client requests, usually equal accepts, unless there because
the connection is refused worker_connections restrictions.
requests: GDP statistics, the total number of requests since the start Nginx sent by the client.
Reading: The current state, Reading client connection requests packets of header.
Writing: current status, the response being transmitted during the packet number of connections to the client.
Waiting: current status, the client is waiting for the connection request issued number of idle open case keep-alive, and this value is equal to active - (reading + writing),

2. Nginx third-party modules:

The third module is a functional expansion of nginx, third-party module requires parameters -add-module when compiling Nginx install the specified path PATH = add some modules by the developer for the company's business needs custom development, there the module is then uploaded to the open-source enthusiasts to develop good conduct github open source modules, nginx support third-party modules need to be recompiled from source support, such as open source echo module

https://github.com/openresty/echo-nginx-module

Installation echo module

Reference Note: https: //github.com/openresty/echo-nginx-module#installation

Compatibility with the echo module nginx: https: //github.com/openresty/echo-nginx-module#compatibility

In nginx has been compiled, and adding echo module

  1. Download echo source package, and stop the current process nginx

    root@z2:/usr/local/src# git clone https://github.com/openresty/echo-nginx-module.git
    root@z2:/usr/local/src# systemctl stop nginx
    
  2. When viewing the current environment does not affect the current nginx compiled parameters in order to configure when adding add-modules

    root@z2:/usr/local/src# nginx -V
    nginx version: nginx/1.16.1
    built by gcc 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04) 
    built with OpenSSL 1.1.1  11 Sep 2018
    TLS SNI support enabled
    configure arguments: --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
    
  3. Switching to the original source package nginx

    root@z2:/usr/local/src# cd nginx-1.16.1/
    
  4. Rebuild compiler environment

    ./configure --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --add-module=/usr/local/src/echo-nginx-module
    
  5. Compile (no make install)

    When the make has been generated for all programs and files, make install just copy the generated files to the appropriate directory, to complete the so-called installation

    root@z2:/usr/local/src/nginx-1.16.1# make
    
  6. The new generation of programs nginx copy them, replace the original nginx main program file, you can restart

    root@z2:/usr/local/src/nginx-1.16.1/objs# mv /apps/nginx/sbin/nginx{,.bak} 
    
    root@z2:/usr/local/src/nginx-1.16.1# cd objs/
    root@z2:/usr/local/src/nginx-1.16.1/objs# cp nginx /apps/nginx/sbin/
    root@z2:/usr/local/src/nginx-1.16.1/objs# systemctl start nginx
    
  7. verification

      location /hello {
    	default_type    text/plain;
        echo  "hello world";
    }
    

    When accessing http://www.mage.net/hello/, it will display hello world;

3. Nginx variables

nginx variables can be referenced in the configuration file, or the log is determined as a function of the use of other scenes, it can be divided into variable and custom built-in variables variables, the variables are built nginx module comes to be acquired by the client many variables access to relevant values.

3.1 built-in variables

Official Documents

The following are common variables

$remote_addr;
#存放了客户端的地址,注意是客户端的公网IP,也就是一家人访问一个网站,则会显示为路由器的公网IP。
$args;
#变量中存放了URL中的指令,例如http://www.magedu.net/main/index.do?id=20190221&partner=search中的id=20190221&partner=search
$document_root
#保存了针对当前资源的请求的系统根目录,如/apps/nginx/html。
$document_uri
#保存了当前请求中不包含指令的URI,注意是不包含请求的指令,比如 http://www.magedu.net/main/index.do?id=20190221&partner=search会被定义为/main/index.do
$host
#存放了请求的host名称。
$http_user_agent
#客户端浏览器的详细信息
$http_cookie
#客户端的cookie信息。
limit_rate 10240;
echo $limit_rate;
#如果nginx服务器使用limit_rate配置了显示网络速率,则会显示,如果没有设置, 则显示0。
$remote_port
#客户端请求Nginx服务器时随机打开的端口,这是每个客户端自己的端口。
$remote_user;
#已经经过Auth Basic Module验证的用户名。
$request_body_file
#做反向代理时发给后端服务器的本地资源的名称。
$request_method
#请求资源的方式,GET/PUT/DELETE等
$request_filename
#当前请求的资源文件的路径名称,由root或alias指令与URI请求生成的文件绝对路径,
如/apps/nginx/html/main/index.html
$request_uri
#包含请求参数的原始URI,不包含主机名,如:/main/index.do?id=20190221&partner=search 。
$scheme
#请求的协议,如ftp,https,http等。
$server_protocol
#保存了客户端请求资源使用的协议的版本,如HTTP/1.0,HTTP/1.1,HTTP/2.0等。
$server_addr
#保存了服务器的IP地址。
$server_name
#请求的服务器的主机名。
$server_port
#请求的服务器的端口号。
3.2 Custom Variables

If desired custom variable name and value, using the instruction set $ variable value ;, is as follows

Context: server, location, if

Syntax: set $variable value; Default: — 
location /zdy {
    default_type    text/plain;
    set $name mage;
    echo $name;
    set $my_port $server_port;
    echo $my_port;
    echo "$server_name:$server_port";
}

Authentication: Access http://www.mage.net/zdy/ the outcome

magedu
80
www.mage.net:80

4. Nginx custom access log

The access log is a record that is the user's specific client requests content information, the global configuration module error_log log is a record level of logging and save the path nginx server is running, so essentially different, but generally only Nginx error log a, but may define a plurality of access log, the log defines a need to save the path in the different access_log specified log server, a log log_format specified format, the format defined in the specific contents of the log to be saved.

4.1 If the source format to retain the log, the log just add the corresponding content, the configuration is as follows:

Add '$ server_name: $ server_port'

http configure

log_format nginx_format1 '$remote_addr - $remote_user [$time_local]"$request" '
                                '$status $body_bytes_sent "$http_referer" '
                                '"$http_user_agent" "$http_x_forwarded_for"' '$server_name:$server_port';

server configured

access_log /data/nginx/logs/www-mage-net_access.log nginx_format1;

verification:

When accessing http://www.mage.net/, the back log has www.mage.net:80

root@z2:~# tail -f /data/nginx/logs/www-mage-net_access.log 

192.168.0.1 - - [12/Mar/2020:10:31:16 +0800]"GET /zdy HTTP/1.1" 200 47 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36" "-"www.mage.net:80

4.2 custom json format of the log

Nginx default access log records the content is relatively simple, the default format is not easy to do post-log statistical analysis, production environments typically
convert json nginx logs for the log, and then do with the use of log collection ELK - statistical - analysis.

That key value mode

log_format access_json '{"@timestamp":"$time_iso8601",'
                                '"host":"$server_addr",'
                                '"clientip":"$remote_addr",'
                                '"size":$body_bytes_sent'
                                '"responsetime":$request_time,'
                                '"upstreamtime":"$upstream_response_time",'
                                '"upstreamhost":"$upstream_addr",'
                                '"http_host":"$host",'
                                '"uri":"$uri",'
                                '"domain":"$host",'
                                '"xff":"$http_x_forwarded_for",'
                                '"referer":"$http_referer",'
                                '"tcp_xff":"$proxy_protocol_addr",'
                                '"http_user_agent":"$http_user_agent",'
                                '"status":"$status"}';

access_log /data/nginx/logs/www-mage-net_access.log  access_json;
{"@timestamp":"2020-03-12T10:48:58+08:00","host":"192.168.1.102","clientip":"192.168.0.1","size":0"responsetime":0.000,"upstreamtime":"-","upstreamhost":"-","http_host":"www.mage.net","uri":"/index.html","domain":"www.mage.net","xff":"-","referer":"-","tcp_xff":"","http_user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36","status":"304"}

5. Nginx compression

Nginx support for the specified type of file is compressed and then transmitted to the client, but also the compression set compression ratio, the file size of the compressed file than the source significantly smaller, which helps reduce the export bandwidth utilization, reduced corporate IT spending, but will take the appropriate CPU resources.

Nginx compressed files is dependent on the function module ngx_http_gzip_module, official documents , configuration instructions are as follows:

#启用或禁用gzip压缩,默认关闭
gzip on | off;
#压缩比由低到高从1到9,默认为1
gzip_comp_level level;
#禁用IE6 gzip功能
gzip_disable "MSIE [1-6]\.";
#gzip压缩的最小文件,小于设置值的文件将不会压缩
gzip_min_length 1k;
#启用压缩功能时,协议的最小版本,默认HTTP/1.1
gzip_http_version 1.0 | 1.1;
#指定Nginx服务需要向服务器申请的缓存空间的个数*大小,默认32 4k|16 8k;
gzip_buffers number size;
#指明仅对哪些类型的资源执行压缩操作;默认为gzip_types text/html,不用显示指定,否则出错
gzip_types mime-type ...;
#如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”
gzip_vary on | off;

example:

gzip on;
gzip_comp_level 5;
gzip_min_length 1k;

gzip_types text/plain application/javascript application/x-javascript
text/cssapplication/xml text/javascript application/x-httpd-php image/jpeg
image/gif image/png;

gzip_vary on;

After compression

mark

mark

No compression before

root@z2:~# ll  /data/nginx/html/pc/test.html 
-rw-r--r-- 1 root root 1086284 Mar 12 11:48 /data/nginx/html/pc/test.html

root@z2:~# curl -I http://www.mage.net/test.html
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 12 Mar 2020 04:01:55 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 1086284
Last-Modified: Thu, 12 Mar 2020 03:48:20 GMT
Connection: keep-alive
ETag: "5e69b104-10934c"
Accept-Ranges: bytes

[Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-9wbB3aYK-1584259839251) (A:% 5Cimage_typoral_used% 5Cimage-20200312120616343.png)]

6. https feature

Web site login page using https are encrypted transmission of encrypted data to ensure data security, HTTPS can encrypt information, so as not to acquire sensitive information by a third party, so the higher level of security many banking sites or e-mail service, etc. will use the HTTPS protocol, HTTPS is actually composed of two parts: HTTP + SSL / TLS, i.e. on an HTTP module added a layer of processing encrypted information. Service and client information transmitted is encrypted by TLS, so after the data transmission is encrypted data.

6.0 https implementation process is as follows:

mark

  1. The client initiates HTTPS requests:

    Client access to a web-side https address, usually port 443

  2. Server configuration

    Using https protocol server must have a certificate, you can apply for some organizations, you can make your own, many domestic sites are do it yourself, when you visit a Web site when prompted certificate indicates that the certificate is not trusted to do their own certificate is a public key and a private key, like a lock and key, under normal circumstances, only the keys you can open your locks, you can give this to someone else locked him in a box, which is filled with money or secret, others do not know what to put inside and others are not open, only your keys can be opened.

  3. Transfer certificate

    The server to the client transfer certificate, in fact, a public key, which contains a lot of information, for example, to obtain a certificate authority, expiration date and so on.

  4. Client certificate parsing

    This part of the work is completed the client, first back to verify the validity of the public key, such as authority, expiration date and so on, if you find a warning box will pop up prompt certificate abnormal there may be a problem, there is no problem if the certificate is generated a random value, and then encrypted with the certificate of the random value, as step 2 said the random value locked up, not allowing people to see.

  5. Encrypted data transfer step 4

    Is to pass a random number for the encryption certificate to the server, the purpose is to allow the server to get this random value, after the communication client and server can be encrypted decrypted by the random value of

  6. The service-side decryption information

    After the random value encrypted using the server private key to decrypt Step 5, to obtain a pass over the client random value (private key), and then the encrypted symmetric content value, and the symmetric encryption private key information is algorithmically mixed together, so unless you know the private key, or is unable to obtain the contents of its internal, but just the client and server are aware of this private key, so long as the secret algorithm can be complicated enough to guarantee the security of the data.

  7. Traffic encryption information

    The server transmitting the private key to encrypt data to the client, the client may be reduced to the original data content.

  8. The client decryption information

    Generation of customers before the end of a private key to decrypt the data obtained pass over the server, because the data has been encrypted, so even if a third party to acquire the data can not know the details.

6.1 ssl configuration parameters

The https nginx function ngx_http_ssl_module implementation module based, so if it is compiled and installed nginx want to use parameter
ngx_http_ssl_module open ssl function, but as a core function of nginx, yum install nginx is turned on by default, compiled and installed nginx need to specify the build parameters - with-http_ssl_module open, official documents , configuration parameters are as follows:

ssl on | off;
#为指定的虚拟主机配置是否启用ssl功能,此功能在1.15.0废弃,使用listen [ssl]替代。

ssl_certificate /path/to/file;
#当前虚拟主机使用使用的公钥文件,一般是crt文件

ssl_certificate_key /path/to/file;
#当前虚拟主机使用的私钥文件,一般是key文件

ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];
#支持ssl协议版本,早期为ssl现在是TSL,默认为后三个

ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
#配置ssl缓存  off: 关闭缓存  none: 通知客户端支持ssl session cache,但实际不支持
#builtin[:size]:使用OpenSSL内建缓存,为每worker进程私有
#[shared:name:size]:在各worker之间使用一个共享的缓存,需要定义一个缓存名称和缓存空间大小,一兆可以存储4000个会话信息,多个虚拟主机可以使用相同的缓存名称。

ssl_session_timeout time;#客户端连接可以复用ssl session cache中缓存的有效时长,默认5m
6.2 self-signed certificate
root@z2:~# cd /apps/nginx/
root@z2:/apps/nginx# mkdir certs
root@z2:/apps/nginx# cd certs/

Fill CN BJ BJ mage rs mage.ca

openssl req -newkey rsa:4096 -nodes -sha256 -keyout ca.key -x509 -days 3650 -out ca.crt

Fill CN BJ BJ mage dev www.mage.net

openssl req -newkey rsa:4096 -nodes -sha256 -keyout www.mage.net.key -out www.mage.net.csr

Issuance of certificate

openssl x509 -req -days 3650 -in www.mage.net.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out www.mage.net.crt

server settings

listen 443 ssl;
ssl_certificate /apps/nginx/certs/www.mage.net.crt;
ssl_certificate_key /apps/nginx/certs/www.mage.net.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
6.3 multi-domain HTTPS

Nginx supports a single IP to achieve multi-domain function, and also supports single domain name on the basis of IP multi implement HTTPS, Nginx is actually based on
SNI (Server Name Indication) function to achieve, SNI is to solve a Nginx server using an IP binding multiple domain names and certificates of
function, and its function is specific to a client sends a domain name (Hostname) to access the sites before connecting to the server to establish an SSL link, this service
is then returned to the client an appropriate certificate in accordance with the domain name .

Each server can be configured with a different certification path

7. About favicon.ico

favicon.ico file icon is displayed when the browser URL collection, when the client uses a browser to ask page, the browser will initiate a request to get their own pages favicon.ico file, but when favicon.ico file browser request when not exist, the server will log record 404, and the browser will display the 404 error. (Curl browser does not)

{"@timestamp":"2020-03-12T18:23:35+08:00","host":"192.168.1.102","clientip":"192.168.0.1","size":548"responsetime":0.000,"upstreamtime":"-","upstreamhost":"-","http_host":"www.mage.net","uri":"/favicon.ico","domain":"www.mage.net","xff":"-","referer":"https://www.mage.net/","tcp_xff":"","http_user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36","status":"404"}

Solution:

1. Do not record logs related

location = /favicon.ico {
    log_not_found off;
    access_log off;
}

2. Set favicon.ico location

For example: the day the cat favicon.ico to your site with the use of

mark

Check the other, the following picture is that small, download

root@z2:~# mkdir /data/nginx/html/pc/images
root@z2:~# cd  /data/nginx/html/pc/images
root@z2:/data/nginx/html/pc/images# wget https://img.alicdn.com/tfs/TB1XlF3RpXXXXc6XXXXXXXXXXXX-16-16.png
root@z2:/data/nginx/html/pc/images# mv TB1XlF3RpXXXXc6XXXXXXXXXXXX-16-16.png  favicon.ico

conf settings:

#location ~ ^/favicon\.ico$ {
location = /favicon.ico {
	root /data/nginx/html/pc/images;
}

verification:

mark

Published 62 original articles · won praise 7 · views 1257

Guess you like

Origin blog.csdn.net/qq_36801585/article/details/104880473