Nginx optimization and anti-leech

1. Hide the version number

1. Steps to hide the version number

You can use the Fiddler tool to grab packets and check the Nginx version,
You can also use the command curl -I http://192.168.160.60 in CentOS to display the response header information.

curl -I http://192.168.160.60

1.1. Method 1: Modify the configuration file method

vim /usr/local/nginx/conf/nginx.conf
http {
    include       mime.types;
    default_type  application/octet-stream;
    server_tokens off;                              #add, close version number
    ......
}

systemctl restart nginx
curl -I http://192.168.160.60

1.2, Method 2: Modify the source code file, recompile and install

vim /opt/nginx-1.12.2/src/core/nginx.h  

#define NGINX_VERSION "1.1.1"                   #Modify version number
 #define NGINX_VER "IIS" NGINX_VERSION          #change server type
  
 cd /opt/nginx-1.12.0/ ./configure --prefix=/usr/local/nginx
 --user=nginx --group=nginx --with-http_stub_status_module make && make install
  
 vim /usr/local/nginx/conf/nginx.conf http {
     include       mime.types;
     default_type  application/octet-stream;
     server_tokens on;  ...... }
     
systemctl restart nginx
curl -I http://192.168.160.60

2. Example operation: hide the version number

2.1. Method 1: Modify the configuration file method

 

 

 

 

 

 

2. Modify users and groups

vim /usr/local/nginx/conf/nginx.conf
user nginx nginx;           
Uncomment, modify user to nginx ,group as nginx

systemctl restart nginx

ps aux | grep nginx
 The main process is run by root Created, the child process is created by nginx create

 

 

3. Cache time

1. Operation steps of cache time

vim /usr/local/nginx/conf/nginx.conf
http {
......
    server {
    ......
        location / {
            root html;
            index index.html index.htm;
        }
         
        location ~ \.(gif|jpg|jepg|png|bmp|ico)$ {      #Add a new location, use the image as the cache object
            root html;
            expires 1d;                                 #Specify the cache time, 1 day
        }
......
    }
}
 
systemctl restart nginx

In Linux system, open Firefox browser, right click and click View Element
Select Network -> select HTML, WS, Other
Visit http://192.168.2.66, double-click the 200 response message to see that the response header contains Cahce-Control:max-age=86400, indicating that the cache time is 86400 seconds. That is to say, it is cached for one day. When the browser accesses this page within one day, the data in the cache is used, and there is no need to re-send the request to the Nginx server, which reduces the bandwidth used by the server.

2. Instance operation: cache time

2.1 Modify the main configuration file

2.2 Incoming pictures and editing web files


  

2.3 Visit in the browser and check whether it is valid

Fourth, log cutting

1. Operation steps of log cutting

vi /opt/fenge.sh
#!/bin/bash
# Filename: fenge.sh
d=$(date -d "-1 day" "+%Y%m%d")                                             #Display the time of the previous day
logs_path="/var/log/nginx"
pid_path="/usr/local/nginx/logs/nginx.pid"
[ -d $logs_path ] || mkdir -p $logs_path                                    #Create log file directory
mv /usr/local/nginx/logs/access.log ${logs_path}/kgc.com-access.log-$d      #Move and rename log files
kill -USR1 $(cat $pid_path)                                                 #Rebuild the new log file
find $logs_path -mtime +30 -exec rm -rf {} \;                               #Delete log files older than 30 days
#find $logs_path -mtime +30 |xargs rm -rf
 
chmod +x /opt/fenge.sh
/opt/fenge.sh
ls /var/log/nginx
ls /usr/local/nginx/logs/access.log
 
crontab -e
0 1 * * * /opt/fenge.sh

tips
In the linux operating system, each file has a lot of time parameters, three of which are mainly ctime, atime, and mtime.

ctime(status time): This time will be updated when the permissions or attributes of the file are modified. ctime is not createtime, but more like change time. This time will only be updated when the attributes or permissions of the file are updated, but This time will not be updated if the content is changed.

atime(accesstime): This time will be updated when the file is used.

mtime(modification time): When the content data of the file is modified, the time will be updated, and if the permissions or attributes are changed, mtime will not change, which is the difference from ctime.

2. Example operation: log cutting

2.1 Writing scripts

2.2 Execute the script to see if log segmentation is implemented

2.3 Do planned tasks and do log segmentation regularly every day

5. Connection timeout

HTTP has a KeepAlive mode, which tells the web server to keep the TCP connection open after processing a request. If other requests from the client are received, the server will use the unclosed connection without establishing another connection

KeepAlive s are kept open for a period of time during which they consume resources. Excessive use can affect performance

1. Operation steps for connection timeout

vim /usr/local/nginx/conf/nginx.conf
http {
......
    keepalive_timeout 65 180;
    client_header_timeout 80;
    client_body_timeout 80;
......
}
 
systemctl restart nginx

keepalive_timeout
Specifies the timeout for KeepAlive. Specifies the maximum time each TCP connection can be maintained, after which the server will close the connection. The default value of Nginx is 65 seconds, and some browsers only keep up to 60 seconds, so it can be set to 60 seconds. Setting it to 0 disables keepalive connections.
The second parameter (optional) specifies the time value in the Keep-Alive:timeout=time response header. This header enables some browsers to actively close the connection so that the server does not have to close the connection. Without this parameter, Nginx will not send the Keep-Alive response header.

client_header_timeout
The timeout for the client to send a complete request header to the server. If the client does not send a complete request header within the specified time, Nginx returns HTTP 408 (Request Timed Out).

client_body_timeout
Specifies the timeout period for sending the request body after the client establishes a connection with the server. If the client does not send anything within the specified time, Nginx returns HTTP 408 (Request Timed Out).

2. Instance operation: connection timeout

2.1 Modify the main configuration file


  

2.2 Browser access test


  

6. Change the number of processes

1. Operation steps to change the number of processes

cat /proc/cpuinfo | grep -c "physical id"   #Check the number of cpu cores
ps aux | grep nginx                         #View how many subprocesses are included in the nginx main process
 
vim /usr/local/nginx/conf/nginx.conf
worker_processes  2;                #Modified to the same or 2 times the number of cores
worker_cpu_affinity 01 10;          #Set each process to be processed by different CPUs, and the number of processes is set to 4:0001 0010 0100 1000
 
systemctl restart nginx

vim /usr/local/nginx/conf/nginx.conf
 
worker processes 2;                            #Modify the number of worker processes to be the same or twice the number of cores
 
worker_cpu_ affinity 01 10;                #Set each process to be processed by different CPUs, the format when the number of processes is set to 4: 0001 0010 0100 1000
 
worker_connections 6000;                 #Modify the maximum number of connections handled by each process
 
#If you increase the number of connections per process, you also need to execute the "ulimit -n 65535" (maximum 65535) command to temporarily modify the maximum number of files that each local process can open at the same time.
 
systemctl restart nginx

  

2. Instance operation: change the number of processes


  

3. The maximum number of process connections (worker_connections) of the change process does not exceed 65535

Restart the service, and increase the number of processes limited by the system limit

Seven, configure web page compression

Nginx's ngx_http_gzip_module compression module provides the function of compressing file content

Allows the Nginx server to compress the output content before sending it to the client to save website bandwidth and improve user experience. It is installed by default

The corresponding compression function parameters can be added to the configuration file to optimize the compression performance

1. Steps to configure web page compression

vim /usr/local/nginx/conf/nginx.conf
http {
......
   gzip on;                         #Uncomment and enable gzip compression
   gzip_min_length 1k;              #Minimum compressed file size
   gzip_buffers 4 16k;              #Compression buffer, size is 4 16k buffers
   gzip_http_version 1.1;           #Compressed version (default 1.1, if the front end is squid2.5, please use 1.0)
   gzip_comp_level 6;               #compression ratio
   gzip_vary on;                    #Support front-end cache server to store compressed pages
   gzip_types text/plain text/javascript application/x-javascript text/css text/xml application/xml application/xml+rss image/jpg image/jpeg image/png image/gif application/x-httpd-php application/javascript application/json;       #Compression type, indicating which web documents have compression enabled
......
}

In the above experiment, the content of the web page has been modified and pictures have been inserted, which are omitted here

cd /usr/local/nginx/html
 first game.jpg file to/usr/local/nginx/html Under contents
vim index.html
......
<img src="meme.jpg"/>             #Insert pictures into web pages
</body>
</html>
 
systemctl restart nginx

test:
In Linux system, open Firefox browser, right click and click View Element
Select Network -> select HTML, WS, Other
visit http://192.168.2.66 , double-click the 200 response message to see that the response header contains Content-Encoding: gzip

2. Example operation: configure web page compression

2.1 Modify the configuration file and restart the service


  

Eight, configure the anti-theft chain

1. Operation steps for configuring anti-leech

vim /usr/local/nginx/conf/nginx.conf
http {
......
    server {
    ......
        location ~*\.(jpg|gif|swf)$ {
            valid_referers *.ly.com ly.com;
            if ( $invalid_referer ) {
                rewrite ^/ http://www.ly.com/error.png;
                #return 403;
            }
        }
    ......
    }
}

~* .(jpg|gif|swf)$ : This regular expression matches case-insensitive files ending in .jpg or .gif or .swf;
valid_referers : Set up trusted websites, pictures can be used normally;
The following URL or domain name: the URL containing the relevant string in the referer;
if statement: if the source domain name of the link is not in the list listed in valid_referers, and $invalid_referer is 1, then perform the following operations, that is, rewrite or return a 403 page.

web page preparation:
Web source host (192.168.2.66)Configuration:
cd /usr/local/nginx/html
 Will game.jpg,error.png file to/usr/local/nginx/html Under contents
vim index.html
......
<img src="wallhaven-j3ewjy.jpg"/>
</body>
</html>
 
echo "192.168.2.66 www.xkq.com" >> /etc/hosts
echo "192.168.2.200 www.wy.com" >> /etc/hosts
 
Hotlink website host (192.168.2.200): 
cd /usr/local/nginx/html
vim index.html
......
<img src="http://www.xkq.com/wallhaven-j3ewjy.jpg"/>
</body>
</html>
 
echo "192.168.2.66 www.xkq.com" >> /etc/hosts
echo "192.168.2.200 www.wy.com" >> /etc/hosts
 
Browser verification on the pirate website host
http://www.weq.com

2. Example operation: configure anti-leech

2.1 Preparation of hotlink host webpage

2.2 The hotlink host temporarily adds the mapping relationship between the domain name and IP

2.3 Browser access to the web page of the hotlink host (the source host must also be mapped during the test)

2.4 Modify the nginx main configuration file of the source host

2.5 Restart the service

2.6 Put in the anti-theft chain picture

Posted by noppie on Wed, 09 Nov 2022 21:41:50 +1030