Nginx advanced configuration

Nginx advanced configuration

Article directory

Nginx status page

Based on the implementation of nginx module NGX ﹣ http ﹣ auth ﹣ basic ﹣ module, when compiling and installing nginx, you need to add the compilation parameter -- withhttp ﹣ stub ﹣ status ﹣ module, otherwise, after the configuration is completed, the monitoring will prompt syntax errors.
  1. Configuration example:
[root@ubuntu ~]#vim /apps/nginx/conf/conf.d/pc.conf 
        location /nginx_status {    # This value can be added to the uri after access.
                stub_status;
                allow 192.168.0.0/16; # Only this segment is allowed to view
                allow 127.0.0.1;      # Only local view allowed
                deny all;             # Refuse all
        }                             # The final meaning is to allow 192.168.0.0/16, 127.0.0.1 (native) and others to reject.
# Reload service
[root@ubuntu ~]#systemctl reload nginx.service 
  1. Status page function
The status page is used to output the basic status information of nginx:
    Example of output information:
    Active connections: 291
    server accepts handled requests
        16630948 16630948 31070465
        The above three numbers correspond to the three values of accept, handled and requests respectively
    Reading: 6 Writing: 179 Waiting: 106
  1. Meaning of values on the status page
Active connections:  The number of client connections that are currently active, including connections waiting for idle connections.
accepts: Total statistical value, Nginx The total number of client requests that have been accepted since startup.
handled: Total statistical value, Nginx The total number of client requests that have been processed since startup, usually equal to accepts,Unless there is a cause.
worker_connections Restrict connections that are denied, etc.
requests: Total statistical value, Nginx The total number of requests from clients since startup.
Reading: Current status, reading the connection number of the client request message header.
Writing: Current status, the number of connections in the process of sending response message to the client.
Waiting: Current status, number of idle connections waiting for client to send request, open keep-alive Under the circumstances,This value is equal to active –
(reading+writing),
  1. Test example

Nginx third party module

The third module is the extension of the function of nginx. The third party module needs to use parameter --add-module=PATH to specify the path when compiling and installing Nginx. Some modules are customized development by the company's developers for business needs.
Some modules are developed by open source enthusiasts and uploaded to github for open source. nginx supports third-party modules that need to be recompiled from source.

For example, open source echo module Here we will demonstrate the compilation and configuration of an echo module.

  1. echo module Download
[root@ubuntu ~]#cd /usr/local/src/  # It is better to put it together with the source directory for easy management.
[root@ubuntu src]#git clone https://github.com/openresty/echo-nginx-module
Cloning into 'echo-nginx-module'...
remote: Enumerating objects: 18, done.
remote: Counting objects: 100% (18/18), done.
remote: Compressing objects: 100% (13/13), done.
remote: Total 3015 (delta 8), reused 11 (delta 5), pack-reused 2997
Receiving objects: 100% (3015/3015), 1.15 MiB | 100.00 KiB/s, done.
Resolving deltas: 100% (1619/1619), done.

[root@ubuntu src]#ll
total 16
drwxr-xr-x  4 root root 4096 Jan 10 20:36 ./
drwxr-xr-x 10 root root 4096 Jan 10 20:36 ../
drwxr-xr-x  6 root root 4096 Jan 10 20:23 echo-nginx-module/
drwxr-xr-x  9 1001 1001 4096 Jan  5 17:11 nginx-1.16.1/
  1. echo module entering (compiling) nginx
[root@ubuntu src]#/apps/nginx/sbin/nginx -V  # Use - V to find the last compiled parameter (note that the last compiled parameter is not the first compiled parameter)
nginx version: nginx/1.16.1
built by gcc 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1) 
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
[root@ubuntu src]#cd nginx-1.16.1/   # Enter the source directory
[root@ubuntu nginx-1.16.1]#systemctl stop nginx.service # Close service before Compilation
# View new add module syntax
[root@ubuntu nginx-1.16.1]#./configure --help|grep add
  --with-http_addition_module        enable ngx_http_addition_module
  --add-module=PATH                  enable external module  # Use this to add new modules
  --add-dynamic-module=PATH          enable dynamic external module
  --with-cc-opt=OPTIONS              set additional C compiler options
  --with-ld-opt=OPTIONS              set additional linker options
  --with-pcre-opt=OPTIONS            set additional build options for PCRE
  --with-zlib-opt=OPTIONS            set additional build options for zlib
  --with-openssl-opt=OPTIONS         set additional build options for OpenSSL
# Add a new module after copying the last compilation parameter
# Start compilation
[root@ubuntu nginx-1.16.1]#Echo module) - add module = / usr / local / SRC / echo nginx-m Odule
[root@ubuntu nginx-1.16.1]#make
[root@ubuntu nginx-1.16.1]#make install
  1. echo module use
  • Example 1:
[root@ubuntu nginx-1.16.1]#vim /apps/nginx/conf/conf.d/pc.conf 
location / {
                root /data/nginx/html/pc;  # Define access root
                default_type text/html;    # Define access as text (because the main configuration defaults to download)
                echo hello world;          # echo a field access display
        }
[root@ubuntu nginx-1.16.1]#/apps/nginx/sbin/nginx -t  # Check syntax
nginx: the configuration file /apps/nginx//conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx//conf/nginx.conf test is successful
# Startup service
[root@ubuntu nginx-1.16.1]#systemctl start nginx.service
  • Example 2:
[root@ubuntu nginx-1.16.1]#vim /apps/nginx/conf/conf.d/pc.conf 
        location /main {
                index index.html;
                default_type text/html;                            # How to view
                echo "hello world,main-->";                        # Fields displayed 
                echo_reset_timer;
                echo_location /sub1;                               # This is the location /sub1 after the call
                echo_location /sub2;                               # This is the location /sub2 after the call
                echo "took $echo_timer_elapsed sec for total.";    # This is a $echo? Timer? Elapsed time calculator
        }
        location /sub1 {      # The location /main call before this location
                echo_sleep 1; # Dormancy for one second
                echo sub1;    # Fields displayed
        }
        location /sub2 {      # The location /main call before this location
                echo_sleep 1; # Dormancy for one second
                echo sub2;    # Fields displayed
        }
[root@ubuntu nginx-1.16.1]#systemctl reload nginx.service 
  1. Test access

Nginx variable use

Nginx variables can be referenced in the configuration file as function judgment or log scenarios. Variables can be divided into built-in variables and user-defined variables. Built in variables are provided by nginx module, through which many values related to client access can be obtained.

Built-in variables

    Common usage of variables:
                    Log record
                    Judgement of value
$remote_addr;
#The address of the client is stored. Note that the public IP address of the client is the public IP address of the router when a family visits a website.

$args#For example, http://www.magedu.net/main/index.do?
id=20190221&partner=search Medium id=20190221&partner=search

$document_root#The system root directory where the request for the current resource is saved, such as / apps/nginx/html.

$document_uri#Save the URI of the current request that does not contain the instruction. Note that it does not contain the requested instruction, such as
http://www.magedu.net/main/index.do?id=20190221&partner=search Will be defined as/main/index.do . 

$host#The requested host name is stored.

$http_user_agent#Client browser details

$http_cookie#cookie information for the client.

limit_rate 10240;
echo $limit_rate;
#If the nginx server is configured with limit rate to display the network rate, it will display, if not set, it will display 0.

$remote_port#The port opened randomly when the client requests the Nginx server, which is the port of each client.

$remote_user#A user name that has been authenticated by the Auth Basic Module.

$request_body_file#The name of the local resource sent to the back-end server when acting as a reverse proxy.

$request_method#How to request resources, GET/PUT/DELETE, etc.

$request_filename#The path name of the currently requested resource file, the absolute path of the file generated by the root or alias instruction and the URI request,
//For example, / apps/nginx/html/main/index.html

$request_uri#The original URI containing the request parameter, excluding the host name, for example, / main / index. Do? Id = 20190221 & partner = search.

$scheme#The requested protocol, such as ftp, https, http, etc.

$server_protocol#Saved the version of the protocol used by the client to request resources, such as HTTP/1.0, HTTP/1.1, HTTP/2.0, etc.

$server_addr#The IP address of the server is saved.

$server_name#The hostname of the requested server.

$server_port#The port number of the requested server.
  • How to use built-in variables (here is an example of a variable.)
[root@ubuntu ~]#vim /apps/nginx/conf/conf.d/pc.conf 
        location / {
                root /data/nginx/html/pc;
                index index.html;
                default_type text/html; # Add this to view in text, if not download.
                echo $remote_port;      # Use the built-in variable to echo directly.
        }
# Check syntax
[root@ubuntu ~]#/apps/nginx/sbin/nginx -t
nginx: the configuration file /apps/nginx//conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx//conf/nginx.conf test is successful
# Reload configuration
[root@ubuntu ~]#systemctl reload nginx.service
  • Test access

Custom variable

If you need to customize the variable name and value, use the instruction set $variable value; as follows:
Syntax: set $variable value; Default: — Context: server, location, if
        set $name magedu;
        echo $name;
        set $my_port $server_port;
        echo $my_port;
        echo "$server_name:$server_port";
  • Custom variable usage example:
[root@ubuntu ~]#vim /apps/nginx/conf/conf.d/pc.conf 
 location / {
                root /data/nginx/html/pc;
                index index.html;
                default_type text/html;
                set $NAME opengsd;
                echo $NAME;
        }
[root@ubuntu ~]#/apps/nginx/sbin/nginx -t
nginx: the configuration file /apps/nginx//conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx//conf/nginx.conf test is successful
[root@ubuntu ~]#systemctl reload nginx.service 
  • Call built-in variable reset
[root@ubuntu ~]#vim /apps/nginx/conf/conf.d/pc.conf 
location / {
                root /data/nginx/html/pc;
                index index.html;
                default_type text/html;
                set $IP $remote_addr;
                echo $IP;
        }
[root@ubuntu ~]#/apps/nginx/sbin/nginx -t
nginx: the configuration file /apps/nginx//conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx//conf/nginx.conf test is successful
[root@ubuntu ~]#systemctl reload nginx.service 
  • Custom variable test access
  • Call built-in variable reset test access

Nginx custom access log

    The access log records the specific request content information of the client or the user. The error log in the global configuration module records the log saving path and the log level when the nginx server is running. Therefore, it is essentially different. There is only one error log in nginx,
    However, access logs can be defined in different server s. To define a log, you need to use access log to specify the saving path of the log, and log format to specify the format of the log. The format defines the specific log content to be saved.

Official documents

Custom default format log

If you want to keep the source format of the log and only add the corresponding log content, the configuration is as follows:

[root@ubuntu ~]#vim /apps/nginx/conf/nginx.conf
        http {           # Must be written in the http field
        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';
        access_log logs/access.log nginx_format1;
        }

#Restart nginx and access the test log format
==> /apps/nginx/logs/access.log <==
192.168.0.1 - - [22/Feb/2019:08:44:14 +0800] "GET /favicon.ico HTTP/1.1" 404 162 "-"
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:65.0) Gecko/2
0100101 Firefox/65.0" "-"www.magedu.net:80

Custom json format log

    The default access log record content of nginx is relatively simple, and the default format is not convenient for log statistical analysis later. In the production environment, nginx logs are usually converted into json logs, and then used with ELK for log collection statistics analysis.
[root@ubuntu ~]#vim /apps/nginx/conf/nginx.conf
http {
    #access_log  logs/access.log  main;
    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 /apps/nginx/logs/access_json.log access_json;  # Call the above log configuration to save to this file.


#Restart Nginx and access the test log format
[root@ubuntu ~]#/apps/nginx/sbin/nginx -t
nginx: the configuration file /apps/nginx//conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx//conf/nginx.conf test is successful
[root@ubuntu ~]#systemctl reload nginx.service 
[root@ubuntu ~]#tail  -f /apps/nginx/logs/access_json.log  # Monitoring log
{"@timestamp":"2020-01-11T15:05:40+08:00","host":"192.168.39.184","clientip":"192.168.39.1","size":23,"responsetime":0.000,"upstreamtime":"-","upstreamhost":"-","http_host":"www.opengsd.net","uri":"/","domain":"www.opengsd.net","xff":"-","referer":"-","tcp_xff":"","http_user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36","status":"200"}
  • You can find the software that parses the json format on the Internet to show that the correct json is correct.
  • Lack of verification

    matters needing attention:
        When the main configuration file configures the json sub configuration, there is no need to configure a log collection. (if you want to collect the logs of each domain name separately, you can configure it in the sub configuration.) it is better to configure the location field for the sub configuration file collection log configuration, rather than the server global field.

Log access statistics in json format

  • python script log access statistics
# Download python2 because it is used for writing
[root@ubuntu ~]#apt install python2.7  

# The best way to prepare logs is to have logs with various status codes (for nginx access logs)
[root@ubuntu logs]#ll access_json.log 
-rw-r--r-- 1 root root 80041 Jan 11 16:01 access_json.log

# Create a script (you must specify the log file when the script is stored or executed in the directory where your log is stored)
[root@ubuntu ~]#cd /apps/nginx/logs/
#!/usr/bin/env python
#coding:utf-8
#Author:Yang Tao
status_200= []
status_404= []
with open("access_json.log") as f:
    for line in f.readlines():
        line = eval(line)
        if line.get("status") == "200":
            status_200.append(line.get)
        elif line.get("status") == "404":
            status_404.append(line.get)
        else:
            print(" ERROR")      # Status code is other printing ERROR
f.close()

print "200--:",len(status_200)   # What is the status code 200
print "404--:",len(status_404)   # What's the status code 400

# Test script log access statistics
[root@ubuntu logs]#python2.7 log.py 
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
200--: 135
404--: 36

Nginx compression function

    Nginx supports compression of files of the specified type and then transfer them to the client. Compression can also set the compression ratio. The compressed file size will be significantly smaller than the source file, which helps to reduce the utilization of the export bandwidth and reduce the IT expenditure of the enterprise, but will occupy the corresponding CPU resources. (it can be placed in the fields of http, server and location)

The file compression function of Nginx depends on the module NGX http gzip module, Official documents:
The configuration instructions are as follows:

#Enable or disable gzip compression, off by default
gzip on | off;

#The compression ratio is from 1 to 9 from low to high, and the default is 1 (the compression ratio is better under 5, and 3 is better). Compression ratio is too high and bandwidth consumption is too high)
gzip_comp_level level;

#Disable IE6 gzip
gzip_disable "MSIE [1-6]\.";

#gzip is the smallest compressed file. Files smaller than the set value will not be compressed
gzip_min_length 1k;

#When compression is enabled, the minimum version of the protocol, HTTP/1.1 by default
gzip_http_version 1.0 | 1.1;

#Specifies the number * size of the cache space that Nginx service needs to apply to the server. The default is 324k| 168k;
gzip_buffers number size;

#Indicates which types of resources are compressed only; the default is gzip_types text/html, do not display the specified, otherwise an error occurs 
gzip_types mime-type ...;
# This file has many compression types
[root@ubuntu logs]#vim /apps/nginx/conf/mime.types


#If compression is enabled, whether to insert "vary: accept encoding" in the header of response message
gzip_vary on | off;

Introduction to the function of mime.type file

  • Modify profile to compression
[root@ubuntu ~]#vim /apps/nginx/conf/nginx.conf
http {
        gzip on;
        gzip_buffers 128 4k;
        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;
     }
  • Prepare test files
[root@ubuntu pc]#ll -h
total 108M
-rw-r--r-- 1 root root 108M Jan 11 17:11 messages.html
  • Test the difference between compression and non compression
# Uncompressed
[root@centos7 ~]#curl -I --compressed www.opengsd.net/messages.html
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Sat, 11 Jan 2020 09:18:28 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 113044372
Last-Modified: Sat, 11 Jan 2020 09:11:04 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "5e199128-6bceb94"
Accept-Ranges: bytes

# compress
[root@centos7 ~]#curl -I --compressed www.opengsd.net/messages.html
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Sat, 11 Jan 2020 09:18:57 GMT
Content-Type: text/html; charset=utf-8
Last-Modified: Sat, 11 Jan 2020 09:11:04 GMT
Connection: keep-alive
Keep-Alive: timeout=60
Vary: Accept-Encoding
ETag: W/"5e199128-6bceb94"
Content-Encoding: gzip   # Compression is shown here

https function

    The login pages of Web sites are transmitted using HTTPS encryption, which encrypts data to ensure the security of data. HTTPS can encrypt information to avoid sensitive information being obtained by third parties. Therefore, many high-level services such as bank websites or e-mail will adopt HTTPS agreement,
    HTTPS is actually composed of two parts: HTTP + SSL / TLS, which is to add a layer of module to process encrypted information on HTTP. The information transmission of the server and the client will be encrypted through TLS, so the data transmitted are encrypted data.


The https implementation process is as follows:

1. Client initiates HTTPS request:
The https address of a web terminal accessed by the client is generally port 443

2. Server configuration:
The servers using https protocol must have a set of certificates, which can be applied for by some organizations or made by themselves. At present, many domestic websites do it by themselves
 When you visit a website and prompt that the certificate is untrustworthy, it means that the certificate is made by yourself. The certificate is a public key and private key, just like a lock and key
 Key. Normally, only your key can open your lock. You can give this to someone to lock a box full of money or secrets
 I don't know what's in it and others can't open it. Only your key can open it.

3. Transmission certificate:
The server delivers the certificate to the client, in fact, it is the public key, which contains a lot of information, such as the certification authority, expiration time and so on.

4. Client resolution certificate:
This part of the work is completed by the client. First, verify the validity of the public key, such as the authority, expiration time, etc. If an exception is found, a pop-up will pop up
 The warning box indicates that there may be a problem with the certificate. If there is no problem with the certificate, generate a random value, and then encrypt the random value with the certificate, as shown in step 2
 Say to lock up the random value so that no one can see it.

5. Transmit encrypted data in 4 steps:
It is to pass the random value encrypted by certificate to the server, so that the server can get the random value, and then the communication between the client and the server can be done
 It is encrypted and decrypted with this random value.

6. Server decrypts information:
After the server decrypts the random value encrypted in 5 steps with the private key, it gets the random value (private key) from the client, and then adds the content symmetrically through the value
 Secret, symmetric encryption is to mix information and private key together by algorithm, so unless you know the private key, you cannot get its internal content, and it is hospitable
 Both client and server know the private key, so as long as the secret algorithm is complex enough, data security can be guaranteed.

7. Transmit encrypted information:
The server will pass the encrypted data to the client, where the original data can be restored.

8. Client decryption information:
The client uses the previously generated private key to obtain and decrypt the data passed by the server. Since the data is always encrypted, even the third party can not know the data
 The details.

ssl configuration parameters

The https function of nginx is implemented based on the module NGX ﹣ http ﹣ SSL ﹣ module. Therefore, if you are compiling and installing nginx, you need to use parameters
NGX > HTTP > ssl > module enables ssl function, but as the core function of nginx, nginx installed from yum is enabled by default. To compile and install nginx, you need to specify the compilation parameter – with HTTP > ssl > module, Official documents:
module.html, the configuration parameters are as follows:

ssl on | off;
#Configure whether to enable the ssl function for the specified virtual host. This function is discarded in 1.15.0 and replaced with listen [ssl].
ssl_certificate /path/to/file;

#The current public key file used by the virtual host is generally a crt file
ssl_certificate_key /path/to/file;

#The private key file used by the current virtual host, usually the key file
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];

#Support ssl protocol version, ssl in the early stage, TSL now, and the last three by default
ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
#Configure ssl cache
        off:  Close cache
        none: Notify client support ssl session cache,But not in practice
        builtin[:size]: Use OpenSSL Built in cache, for every worker Process private
        [shared:name:size]: In each worker To use a shared cache, you need to define a cache name and cache space size, 1 trillion
//4000 session information can be stored, and multiple virtual hosts can use the same cache name.

ssl_session_timeout time;#The client connection can reuse the effective length of cache in ssl session cache, which is 5m by default

Self signed certificate

#Self signed CA certificate
[root@s2 ~]# cd /apps/nginx/
[root@s2 nginx]# mkdir certs
[root@s2 nginx]# cd certs/
[root@s2 nginx]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout ca.key -x509 -
days 3650 -out ca.crt #Self signed CA certificate
Generating a 4096 bit RSA private key
.................++
.....
Country Name (2 letter code) [XX]:CN #Country code, https://country-code.cl/
State or Province Name (full name) []:BeiJing #Province
Locality Name (eg, city) [Default City]:Beijing #City name
Organization Name (eg, company) [Default Company Ltd]:magedu.Ltd #Corporate name
Organizational Unit Name (eg, section) []:magedu #department
Common Name (eg, your name or your server's hostname) []:magedu.ca #Generic name
Email Address []:2973707860@qq.com #mailbox
[root@s2 certs]# ll ca.crt
-rw-r--r-- 1 root root 2118 Feb 22 12:10 ca.crt
#Self made key and csr files
[root@s2 certs]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout www.magedu.net.key
-out www.magedu.net.csr
Generating a 4096 bit RSA private key
........................................................................++
......
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:BeiJing
Locality Name (eg, city) [Default City]:BeiJing
Organization Name (eg, company) [Default Company Ltd]:magedu.net
Organizational Unit Name (eg, section) []:magedu.net
Common Name (eg, your name or your server's hostname) []:www.magedu.net
Email Address []:2973707860@qq.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@s2 certs]# ll
total 16
-rw-r--r-- 1 root root 2118 Feb 22 12:10 ca.crt
-rw-r--r-- 1 root root 3272 Feb 22 12:10 ca.key
-rw-r--r-- 1 root root 1760 Feb 22 12:18 www.magedu.net.csr
-rw-r--r-- 1 root root 3272 Feb 22 12:18 www.magedu.net.key
#grant a certificate
[root@s2 certs]# openssl x509 -req -days 3650 -in www.magedu.net.csr -CA ca.crt -CAkey
ca.key -CAcreateserial -out www.magedu.net.crt
Signature ok
subject=/C=CN/ST=BeiJing/L=BeiJing/O=magedu.net/OU=magedu.net/CN=www.magedu.net/emailAdd
ress=2973707860@qq.com
Getting CA Private Key
#Verify certificate content
[root@s2 certs]# openssl x509 -in www.magedu.net.crt -noout -text
Certificate:
        Data:
                Version: 1 (0x0)
                Serial Number:
                        bb:76:ea:fe:f4:04:ac:06
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=CN, ST=BeiJing, L=Beijing, O=magedu.Ltd, OU=magedu,
CN=magedu.ca/emailAddress=2973707860@qq.com
        Validity
                Not Before: Feb 22 06:14:03 2019 GMT
                Not After : Feb 22 06:14:03 2020 GMT
        Subject: C=CN, ST=BeiJing, L=BeiJing, O=magedu.net, OU=magedu.net,
CN=www.magedu.net/emailAddress=2973707860@qq.com
        Subject Public Key Info:
                Public Key Algorithm: rsaEncryption
                Public-Key: (4096 bit)

Nginx certificate configuration

listen 80;
listen 443 ssl;
ssl_certificate /apps/nginx/certs/www.magedu.net.crt;
ssl_certificate_key /apps/nginx/certs/www.magedu.net.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
#Restart Nginx and access authentication

Implement multi domain HTTPS

Nginx supports the function of multiple domain names based on a single IP, and also supports the realization of HTTPS based on a single IP and multiple domain names. In fact, SNI is based on the SNI (Server Name Indication) function of nginx. SNI is to solve the problem of using an IP to bind multiple domain names and certificates in a nginx server. Its specific function is that the client sends before connecting to the server to establish SSL link Send the host name of the site to be visited, so that the server will return a suitable certificate to the client according to the domain name.

#Making key and csr files
[root@s2 certs]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout
mobile.magedu.net.key -out mobile.magedu.net.csr
Generating a 4096 bit RSA private key
..........
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:BeiJing
Locality Name (eg, city) [Default City]:BeiJing
Organization Name (eg, company) [Default Company Ltd]:magedu
Organizational Unit Name (eg, section) []:magedu
Common Name (eg, your name or your server's hostname) []:mobile.magedu.net
Email Address []:2973707860@qq.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
#Signature certificate
[root@s2 certs]# openssl x509 -req -days 3650 -in mobile.magedu.net.csr -CA ca.crt -
CAkey ca.key -CAcreateserial -out mobile.magedu.net.crt
Signature ok
subject=/C=CN/ST=BeiJing/L=BeiJing/O=magedu/OU=magedu/CN=mobile.magedu.net/emailAddress=
2973707860@qq.com
Getting CA Private Key
#Verify certificate content
[root@s2 certs]# openssl x509 -in mobile.magedu.net.crt -noout -text
Certificate:
        Data:
                Version: 1 (0x0)
                Serial Number:
                        bb:76:ea:fe:f4:04:ac:07
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=CN, ST=BeiJing, L=Beijing, O=magedu.Ltd, OU=magedu,
CN=magedu.ca/emailAddress=2973707860@qq.com
        Validity
                Not Before: Feb 22 13:50:43 2019 GMT
                Not After : Feb 19 13:50:43 2029 GMT
        Subject: C=CN, ST=BeiJing, L=BeiJing, O=magedu, OU=magedu,
CN=mobile.magedu.net/emailAddress=2973707860@qq.com
        Subject Public Key Info:
                Public Key Algorithm: rsaEncryption
                        Public-Key: (4096 bit)
..............
#Nginx configuration
[root@s2 certs]# cat /apps/nginx/conf/conf.d/mobile.conf
server {
listen 80;
server_name mobile.magedu.net;
location / {
root html;
index index.html index.htm;
}
location /linux38 {
root /data/nginx/mobile/html;
index index.html index.htm;
}
location /python {
root /data/nginx/mobile/html;
index index.html index.htm;
}
}
server {
listen 443 ssl;
server_name mobile.magedu.net;
ssl_certificate /apps/nginx/certs/mobile.magedu.net.crt;
ssl_certificate_key /apps/nginx/certs/mobile.magedu.net.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
location / {
root html;
index index.html index.htm;
}
location /linux38 {
root /data/nginx/mobile/html;
index index.html index.htm;
}
location /python {
root /data/nginx/mobile/html;
index index.html index.htm;
}
}

About favicon.ico

The favicon.ico file is the icon displayed when the browser collects the web address. When the client uses the browser to ask for the page, the browser will initiatively request to obtain the favicon.ico file of the page. However, when the favicon.ico file requested by the browser does not exist, the server will record the 404 log, and the browser will also display the 404 error.
terms of settlement:

#1:  Server does not log access:
#location = /favicon.ico {
#log_not_found off;
#access_log off;
#}
#2:  Save icon to specified directory access:
#location ~ ^/favicon\.ico$ {
location = /favicon.ico {
root /data/nginx/html/pc/images;
expires 90d; #Set file expiration time
}

Security options

Hide Nginx version number:

Change nginx source information and recompile nginx

# vim src/http/ngx_http_header_filter_module.c
49 static u_char ngx_http_server_string[] = "Server: linux38" CRLF; #Define the
server Field information

Upgrade OpenSSL version:

Heartbleed, also referred to as "heartbleed vulnerability", is a security vulnerability in OpenSSL, which is widely used to implement the transport layer security (TLS) protocol of the Internet. It was introduced into the software in 2012 and first disclosed to the public in April 2014. As long as a defective OpenSSL instance is used, both the server and the client may be attacked. The reason for this problem is that the input is not properly validated (lack of boundary checking) when implementing the heartbeat extension of TLS, so the name of the vulnerability comes from heartbeat. This program error belongs to buffer over reading, that is, more data can be read than should be allowed to read.

Get ready OpenSSL Source package:
# pwd
/usr/local/src
# tar xvf openssl-1.1.1d
//Compile and install Nginx and develop a new version of OpenSSL path:
# cd /usr/local/src/nginx-1.16.1/
#./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 --withhttp_
gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --withstream_
realip_module --with-select_module --with-file-aio --addmodule=/
usr/local/src/echo-nginx-module --with-openssl=/usr/local/src/openssl-1.1.1d
# make && make install
//Verify and start Nginx:
# /apps/nginx/sbin/nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
# /apps/nginx/sbin/nginx

Published 19 original articles, won praise 4, visited 411
Private letter follow

Tags: Nginx Ubuntu OpenSSL SSL

Posted on Sat, 11 Jan 2020 05:23:15 -0500 by PhilVaz