Nginx Security & Tuning

Nginx Security & Tuning

1. Hidden version number

Modify source code before Compilation
[root@study nginx-1.16.1]# vim src/core/nginx.h 	
Change the following line
 13 #define NGINX_VERSION      "1.16.1"
 14 #define NGINX_VER          "nginx/" NGINX_VERSION

[root@study nginx-1.16.1]# vim src/http/ngx_http_header_filter_module.c 
Repair this line Server: After the name is OK
 49 static u_char ngx_http_server_string[] = "Server: nginx" CRLF;

2. Modifying Users

[root@study ~]# vim /usr/local/nginx/conf/nginx.conf
 user  nginx;
[root@study ~]# useradd -M -s /sbin/nologin nginx
[root@study ~]# /usr/local/nginx/sbin/nginx -s reload
[root@study ~]# lsof -i :80
nginx   7890  root    6u  IPv4  38505      0t0  TCP *:http (LISTEN)
nginx   7942 nginx    6u  IPv4  38505      0t0  TCP *:http (LISTEN)

3. Modify the Number of nginx Running Processes (Nginx Running Processes Number Usually We Set CPU Core or Core Number x2)

[root@study ~]# vim /usr/local/nginx/conf/nginx.conf
3 worker_processes  1;-->worker_processes  4;
[root@study ~]# /usr/local/nginx/sbin/nginx -s reload
[root@study ~]# lsof -i :80
nginx   7890  root    6u  IPv4  38505      0t0  TCP *:http (LISTEN)
nginx   7947 nginx    6u  IPv4  38505      0t0  TCP *:http (LISTEN)
nginx   7948 nginx    6u  IPv4  38505      0t0  TCP *:http (LISTEN)
nginx   7949 nginx    6u  IPv4  38505      0t0  TCP *:http (LISTEN)
nginx   7950 nginx    6u  IPv4  38505      0t0  TCP *:http (LISTEN)

4. The maximum number of files opened by nginx

Add to:
worker_rlimit_nofile 102400; * This instruction refers to the maximum number of file descriptors open when an nginx process,
events {
     use epoll;  IO multiplexing
     worker_connections  102400;
select, poll and epoll are all mechanisms of IO multiplexing. I/O multiplexing can monitor multiple descriptors through a mechanism. Once a descriptor is ready (usually read or write), it can notify the program to read and write accordingly.
View the maximum number of files
[root@study ~]# cat /proc/sys/fs/file-max 

epoll advantages:
1. Epoll has no limit on maximum concurrent connection. The upper limit is the maximum number of files that can be opened. This number is generally much larger than 2048. Generally speaking, this number has a great relationship with system memory. The specific number can be viewed by cat/proc/sys/fs/file-max.
[root@xuegod63 nginx-1.12.2]# cat /proc/sys/fs/file-max
 2. Efficiency improvement, Epoll's greatest advantage is that it only cares about your "active" connections, but has nothing to do with the total number of connections, so in the actual network environment, Epoll's efficiency will be much higher than select and poll.
3. Memory copy. Epoll uses "shared memory" on this point. This memory copy is also omitted.

5. Open efficient transmission mode

[root@study ~]# vim /usr/local/nginx/conf/nginx.conf
sendfile        on;
Open efficient file transfer mode. Sendfile instruction specifies whether nginx calls sendfile function to output files. For common applications, it is on. If it is used for downloading and other application disk IO overload applications, it can be set off to balance disk and network I/O processing speed and reduce system load.
tcp_nopush     on;
In order to be effective, the sendfile mode must be opened to prevent network congestion and actively reduce the number of network message segments.

6. Connection timeout

[root@study ~]# vim /usr/local/nginx/conf/nginx.conf	
     #keepalive_timeout  0;
     keepalive_timeout  65;
     tcp_nodelay on;
     client_header_timeout 15;
     client_body_timeout 15;
     send_timeout 15;
keepalived_timeout  The client connection maintains the session timeout time, beyond which the server disconnects the link
tcp_nodelay´╝ŤPrevent network congestion, but include keepalived Parameters are valid
client_header_timeout  The client request header reads the timeout time, if no data is sent beyond the set time. nginx Will return request time out Errors
client_body_timeout  The client asked the principal for a timeout time, and no data was sent beyond that time. The same error message as above
send_timeout  Response to client timeout, which is limited to the time between two activities. If this time exceeds, the client has no activity. nginx Close the connection

7. Limit file upload size

http {
client_max_body_size 10m;


Official Documents

FastCGI interface adopts C/S structure, which can separate HTTP server from script parsing server and start one or more script parsing daemons on the script parsing server. Each time an HTTP server encounters a dynamic program, it can directly deliver it to the FastCGI process for execution, and then return the results to the browser. This way can enable HTTP server to process static requests exclusively or return the results of dynamic script server to client, which greatly improves the performance of the whole application system.

Simply put, fastcgi is an interface between static and dynamic services

Nginx does not support direct invocation or parsing of external programs. All external programs (including PHP) must be invoked through the FastCGI interface. The FastCGI interface is a socket under Linux (this socket can be either a file socket or an ip socket). To call a CGI program, you also need a wrapper of FastCGI (wrapper can be understood as a program used to start another program), which is bound to a fixed socket, such as a port or a file socket. When Nginx sends a CGI request to the socket, wrapper receives the request through the FastCGI interface, and then generates a new thread that calls the interpreter or external program to process the script and read the returned data; then wrapper sends the returned data through the FastCGI interface along the fixed socket. Pass it to Nginx; finally, Nginx sends the returned data to the client.

[External link picture transfer failure (img-DdKv6TBG-1568101768804) (C: Users lpf Desktop fastcgi. jpg)]

fastcgi_connect_timeout 300;    #Specifies the time-out for linking to the back-end FastCGI.
fastcgi_send_timeout 300;       #The time-out for sending requests to FastCGI is the time-out for sending requests to FastCGI after two handshakes have been completed.
fastcgi_read_timeout 300;       #Specifies the timeout time to receive a FastCGI response. This value refers to the timeout time to receive a FastCGI response after two handshakes have been completed.
fastcgi_buffer_size 64k;        #Specifies the size of the buffer required to read the first part of the FastCGI response. This value indicates that the first part of the response (the response header) will be read using a 64 KB buffer. It can be set to the size of the buffer specified by the fastcgi_buffers option.
fastcgi_buffers 4 64k;  #Specifies how many and how many buffers are needed locally to buffer FastCGI response requests.
fastcgi_busy_buffers_size 128k; #It is recommended to set it to twice as fast cgi_buffer and buffer in busy times.
fastcgi_temp_file_write_size 128k;  #How big database will be used when writing fastcgi_temp_path? The default value is twice that of fastcgi_buffers. Setting the above value for an hour may report 502Bad Gateway if the load comes up.
fastcgi_cache gnix; #Represents opening the FastCGI cache and specifying a name for it. Opening the cache is very useful, it can effectively reduce the CPU load and prevent 502 errors, but opening the cache may also cause other problems, depending on the specific circumstances.
fastcgi_cache_valid 200 302 1h; #Used to specify the caching time of the reply code. The value in the instance indicates that the 200 and 302 replies will be cached for one hour, which should be used in conjunction with fastcgi_cache.
fastcgi_cache_valid 301 1d;     #Cache 301 replies for one day
fastcgi_cache_valid any 1m;     #Cache other replies for 1 minute
fastcgi_cache_min_uses 1;       #Number of requests
fastcgi_cache_path              #Define the path of the cache

//Modify the nginx.conf configuration file and add the following to the http tag:
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
#fastcgi_temp_path /data/ngx_fcgi_tmp;
fastcgi_cache_path /data/ngx_fcgi_cache   levels=2:2   #Cache path, Level 2 directory hierarchy
keys_zone=ngx_fcgi_cache:512m  #Define a storage area name, cache size
inactive=1d max_size=40g;      #How long is the inactive data in the cache and the total directory size

9. gzip module

gzip on;        #Turn on compression function
gzip_min_length  1k;    #Set the minimum number of bytes allowed to compress pages.
gzip_buffers     4 32k; #Compression buffer size, which means that the application for 4 units of 32K memory as the compressed result stream cache, the default value is to apply for the same size of memory as the original data to store gzip compression results.
gzip_http_version 1.1; #Compressed version (default 1.1, squid 2.5 front-end use 1.0) is used to set the identification HTTP protocol version, default is 1.1, most browsers have now supported GZIP decompression, use default can be used.
gzip_comp_level 6;  #Compression ratio, used to specify GZIP compression ratio, 1 compression ratio is the smallest, processing speed is the fastest, 9 compression ratio is the largest, transmission speed is fast, processing speed is slow, and CPU resources are also consumed.
gzip_types  text/css text/xml application/javascript;   #Used to specify the type of compression,'text/html'type is always compressed.
gzip_vary on;   #Variheader support, which allows the front-end caching server to cache GZIP-compressed pages.

//Configuration file
gzip on;
gzip_min_length  1k;
gzip_buffers     4 32k;
gzip_http_version 1.1;
gzip_comp_level 9;
gzip_types  text/css text/xml application/javascript;
gzip_vary on;

10. Access Control of Directory Files

(1)No access images Catalogue(php|php5|.sh|.py|.pl)file
//Location ~^/ images/(directory 1 | directory 2)
[root@study ~]# vim /usr/local/nginx/conf/nginx.conf
location ~ ^/images/.*\.(php|php5|.sh|.py|.pl)$ {
             deny all;
[root@study ~]# /usr/local/nginx/sbin/nginx -s reload
[root@study ~]# mkdir /usr/local/nginx/html/images
[root@study ~]# cat /usr/local/nginx/html/images/index.php 
//Access will display 403 errors

(2)url redirect
[root@study ~]# /usr/local/nginx/sbin/nginx -s reload
[root@study ~]# echo 'test' > /usr/local/nginx/html/test.txt
     location ~* \.(txt|doc)$ {
                if ( -f $request_filename) {
                root /usr/local/nginx/html;
                rewrite ^/(.*)$ last;
//When we visit http://IP/test.txt, we redirect to

(3)Restrict directories
//Return 404 when accessing dir1 and 403 when accessing dir2
[root@study ~]# mkdir /usr/local/nginx/html/{dir1,dir2}
[root@study ~]# echo "dir1"  > /usr/local/nginx/html/dir1/index.html
[root@study ~]# echo "dir2"  > /usr/local/nginx/html/dir2/index.html
         location /dir1/ {return 404;}
         location /dir2/ {return 403;}
[root@study ~]#  /usr/local/nginx/sbin/nginx -s reload

(4)Source access control: ngx_http_access_module Modular
                 location ~/ {
                 deny;	#Reject this ip segment

11. Authentication

[root@study ~]# vim /usr/local/nginx/conf/nginx.conf
		location /dir1/ {
             auth_basic "auth";
             auth_basic_user_file /usr/local/nginx/conf/passwd;
 test User, generate password file
[root@study ~]# htpasswd -c /usr/local/nginx/conf/passwd test
New password: 
Re-type new password: 
Adding password for user test
[root@study ~]# chmod 400 /usr/local/nginx/conf/passwd 
[root@study ~]# chown nginx /usr/local/nginx/conf/passwd 

12. Control access times to limit ngx_http_limit_conn_module

Controlling the number of visits to a single IP or domain name, not all connections are counted only when the server is processing the request and has read the entire request header.
   location / {
            root   html;
            limit_conn addr 1;

Tags: Nginx vim socket network

Posted on Tue, 10 Sep 2019 01:00:05 -0700 by buzz