Grandma often says Nginx optimization and anti-theft chain, that's it?

Keywords: Linux Operation & Maintenance CentOS Nginx server

introduction

In the enterprise information application environment, the security and response speed of the server need to configure the response parameters according to the actual situation to achieve the optimal user experience. The default Nginx installation parameters can only provide the most basic services, and also need to reconcile the response parameters such as web page cache time, connection timeout, web page compression, etc. in order to play the maximum role of the server

Nginx optimization and anti-theft chain

1, Hide version number

You can use the Fiddler tool to grab packets and view the Nginx version, or you can use the command curl - I in CentOS http://192.168.184.20 Display the header information of the response message.

curl -I http://192.168.184.20

Method 1: modify the configuration file mode

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.184.20


Method 2: modify the source file and recompile the installation

vim /opt/nginx-1.12.0/src/core/nginx.h
#define NGINX_VERSION "1.1.1" 					#Modified version number
#define NGINX_VER "IIS" NGINX_VERSION 			#Modify 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.184.20

2, Modify users and groups

vim /usr/local/nginx/conf/nginx.conf
user nginx nginx; 								#Cancel the comment and change the user to nginx and the group to nginx

systemctl restart nginx

ps aux | grep nginx
 Main process by root Created by nginx establish

3, 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 and take the picture as the cache object
			root html;
			expires 1d;									#Specify cache time, 1 day
		}
......
	}
}

systemctl restart nginx


In Linux system, open Firefox browser and right-click to view elements
Select network - > select HTML, WS, other
visit http://192.168.80.10 , 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, the time of caching for one day. The browser accesses this page within one day by using the data in the cache without sending a new request to the Nginx server, which reduces the bandwidth used by the server.

4, Log cutting

vim /fenge.sh
#!/bin/bash

d=$(date -d "-1 day" "+%Y%m%d")                 #Displays the time of the previous day
logs_path="/var/log/nginx"
pid_path=`cat /usr/local/nginx/logs/nginx.pid`

[ -d $logs_path ] || mkdir -p $logs_path        #Create log file directory

#Move and rename log files
mv /usr/local/nginx/logs/access.log ${logs_path}/kgc.com-access.log-{$d}

#Rebuild log file
kill -USR1 $pid_path
#Delete log files 30 days ago                   
find $logs_path -mtime +30 -exec rm -rf {} \;
#find $logs_path -mtime +30 |xargs rm -rf



source fenge.sh
ls /var/log/nginx
ls /usr/local/nginx/logs/access.log 

crontab -e
0 1 * * * /root/fenge.sh


Little knowledge

In the linux operating system, each file has many time parameters, of which three are more important: CTime, atime and mtime

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

atime(accesstime):
This time is updated when this file is used.

mtime(modification time):
When the content data of the file is modified, the time will be updated, but the permissions or attributes will not be changed. This is the difference between mtime and ctime.

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 are received from the client, the server will use the unclosed connection without establishing another connection.
KeepAlive remains open for a period of time, during which time they occupy resources. Taking up too much will affect performance.

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
Specify the timeout for keepalive. Specify how long each TCP connection can last, after which the server will close the connection. The default value of Nginx is 65 seconds. Some browsers only hold it for 60 seconds at most, so it can be set to 60 seconds. If it is set to 0, keepalive connection is disabled.
The second parameter (optional) specifies the time value in the response header keep alive: timeout = time. 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 a 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 for sending request body after the client establishes a connection with the server. If the client does not send any content within the specified time, Nginx returns HTTP 408 (Request Timed Out).

6, Change the number of processes

cat /proc/cpuinfo | grep -c "physical id"	#View cpu cores
ps aux | grep nginx							#See how many child processes are included in the nginx main process


vim /usr/local/nginx/conf/nginx.conf
worker_processes  2;				#Change to the same or twice the number of cores
worker_cpu_affinity 01 10;			#Set that each process is processed by different CPUs, and the number of processes is 0001 0010 0100 1000 

systemctl restart nginx

7, 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, with a size of 4 16k buffers
   gzip_http_version 1.1;   		#Compressed version (default: 1.1, if the front end is squid 2.5, please use 1.0)
   gzip_comp_level 6;       		#compression ratio
   gzip_vary on;					#Support the 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 enable compression
...... 
}


cd /usr/local/nginx/html
 First game.jpg File transfer/usr/local/nginx/html Directory
vim index.html
...... 
<img src="game.jpg"/>				#Insert picture in web page
</body>
</html>

systemctl restart nginx



stay Linux In the system, open Firefox browser and right-click to view elements
 Select network ---> choice HTML,WS,other 
visit http://192.168.184.20, double-click the 200 response message to see that the response header contains content encoding: gzip

8, Configure anti-theft chain

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





~*(jpg|gif|jepg|bmp|ico) $: this regular expression represents a case insensitive file ending in. JPG or. GIF or. swf;
valid_referers: set up trusted websites and use pictures 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 valid_ In the list listed by referers, $invalid_ If the referer is 1, perform the following operations, that is, rewrite or return to page 403.

Web page preparation:
Web source host (192.168.184.20)

cd /usr/local/nginx/html
 take kiki.jpg,error.png File transfer/usr/local/nginx/html Directory
vim index.html
...... 
<img src="kiki.jpg"/>
</body>
</html>

echo "192.168.184.20 www.lic.com" >> /etc/hosts 
echo "192.168.184.30  www.daodao.com" >> /etc/hosts 


Stealing website host (192.168.184.30)

cd /usr/local/nginx/html
vim index.html
...... 
<img src="http://www.lic.com/kiki.jpg"/>
</body>
</html>

echo "192.168.184.20 www.lic.com" >> /etc/hosts 
echo "192.168.184.30 www.daodao.com" >> /etc/hosts 



Verify the browser on the host of the map stealing website

http://www.daodao.com

9, fpm parameter optimization

vim /usr/local/php/etc/php-fpm.conf 
pid = run/php-fpm.pid

vim /usr/local/php/etc/php-fpm.d/www.conf

– line 96 –

pm = dynamic				#fpm process startup mode, dynamic

– line 107 –

pm.max_children=20			#Maximum number of processes started by fpm process

– line 112 –

pm.start_servers = 5		#The number of processes started by default when starting in dynamic mode is between the minimum and maximum

– line 117 –

pm.min_spare_servers = 2	#Minimum number of idle processes in dynamic mode

– line 122 –

pm.max_spare_servers = 8	#Maximum number of idle processes in dynamic mode


kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`			#Restart PHP FPM
netstat -anpt | grep 9000

summary

Nginx: a service that handles static requests (what it excels at)

Features: the theoretical value of 30000-50000 is concurrent, which is affected by the CPU and the maximum number of file openings

Lightweight:
Rich functions (open source + charging)
Defect: cluster is not supported by default
① Configuration file composition:

Global global module configuration
http {} module configuration
server module
location matches URL and path
② What modules does Nginx have

status
rewrite
FPM
virtual_ host virtual host
gzip
tokens off
③ NG optimization

Anti theft chain
 Hidden version——>①configuration file ②Source code-->The installation needs to be recompiled
 Modify users and groups
 Cache time
 Log segmentation
 Web page compression——>gzip->Manage the compression ratio, the size of the minimum compressed object, the number and size of buffers saved by compression, and whether the front-end cache is saved——>Temporary cache file/Permission adjustment of directory
 connection timed out
FPM
work Work process resource allocation
 Virtual host based: IP/port/domain name

Posted by nicelad_uk on Wed, 13 Oct 2021 18:32:05 -0700