Nginx优化与 SSL/TLS配置

发布于:2025-09-12 ⋅ 阅读:(27) ⋅ 点赞:(0)

1、隐藏版本号

可以使用Fiddler工具抓取数据包,查看Nginx版本,也可以在CentOS中使用命令curl -I
http://192.168.10.23 显示响应报文首部信息。

方法一:

方法一:修改配置文件方式
vim /usr/local/nginx/conf/nginx.conf
http {
    include       mime.types;
    default_type  application/octet-stream;
    server_tokens off;			 			#添加,关闭版本号
    ......
}

systemctl restart nginx
curl -I http://192.168.17.155

方法二:

vim /opt/nginx-1.22.0/src/core/nginx.h
#define NGINX_VERSION "1.1.1" 					#修改版本号
#define NGINX_VER "IIS" NGINX_VERSION 			#修改服务器类型

cd /opt/nginx-1.22.0/ 
./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module \
--with-http_ssl_module

make

cp /opt/nginx-1.22.0/objs/nginx /usr/local/nginx/sbin/nginx


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

2、修改用户与组

vim /usr/local/nginx/conf/nginx.conf
user nginx nginx; 				#取消注释,修改用户为 nginx ,组为 nginx

systemctl restart nginx

ps aux | grep nginx
主进程由root创建,子进程由nginx创建

3、缓存时间

----------------缓存时间-------------------
当Nginx将网页数据返回给客户端后,可设置缓存的时间,以方便在日后进行相同内容的请求
时直接返回,避免重复请求,加快了访问速度一般针对静态网页设置,对动态网页不设置缓存时间
​vim /usr/local/nginx/conf/nginx.conf
http {
......    
      server {    
      ......         
          location / {            
               root html;            
               index index.html index.htm;        
           }        ​        
          location ~ \.(gif|jpg|jepg|png|bmp|ico)$ {  
              #加入新的 location,以图片作为缓存对象            
               root html;            
               expires 1d;                      #指定缓存时间,1天        
           }​
......    
       }
 }​
#重启服务systemctl restart nginx
在Linux系统中,打开火狐浏览器,右击点查看元素选择 网络 ---> 选择 HTML、WS、其他 访问
http://192.168.17.155/yjs805.png ,双击200响应消息查看响应头中包含 Cahce-Control:
max-age=86400 表示缓存时间是 86400 秒。也就是缓存一天的时间,一天之内浏览器访问这个页
面,都是用缓存中的数据,而不需要向 Nginx 服务器重新发出请求,减少了服务器的使用带宽。

4、日志切割

----------------日志切割-------------------
vim /opt/fenge.sh
#!/bin/bash
# Filename: fenge.sh
day=$(date -d "-1 day" "+%Y%m%d")					#显示前一天的时间
logs_path="/var/log/nginx"
pid_path="/usr/local/nginx/logs/nginx.pid"
[ -d $logs_path ] || mkdir -p $logs_path 			#创建日志文件目录
mv /usr/local/nginx/logs/access.log ${logs_path}/kgc.com-access.log-$day	
#移动并重命名日志文件
kill -USR1 $(cat $pid_path)							#重建新日志文件
find $logs_path -mtime +30 -exec rm -rf {} \;		#删除30天之前的日志文件
#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

5、连接超时

----------------连接超时-------------------
HTTP有一个KeepAlive模式,它告诉web服务器在处理完一个请求后保持这个TCP连接的打开状态。
若接收到来自同一客户端的其它请求,服务端会利用这个未被关闭的连接,而不需要再建立一个连
接。KeepAlive 在一段时间内保持打开状态,它们会在这段时间内占用资源。占用过多就会影响性能。

vim /usr/local/nginx/conf/nginx.conf
http {
...... 
    keepalive_timeout 65 180;      三次握手的超时时间
    client_header_timeout 80;       等待客户端发送请求头的超时时间会送408 错误
    client_body_timeout 80;          设置客户端发送请求体的超时时间
...... 
}

systemctl restart nginx
---------------------------------------------------------------------------------
#keepalive_timeout
指定KeepAlive的超时时间(timeout)。指定每个TCP连接最多可以保持多长时间,服务器将会在这
个时间后关闭连接。 Nginx的默认值是65秒,有些浏览器最多只保持 60 秒,所以可以设定为 60 秒。
若将它设置为0,就禁止了keepalive 连接。
第二个参数(可选的)指定了在响应头Keep-Alive:timeout=time中的time值。这个头能够让一些浏览
器主动关闭连接,这样服务器就不必去关闭连接了。没有这个参数,Nginx 不会发送 Keep-Alive 响应
头。

##client_header_timeout
客户端向服务端发送一个完整的 request header 的超时时间。如果客户端在指定时间内没有发送一个
完整的 request header,Nginx 返回 HTTP 408(Request Timed Out)。

###client_body_timeout
指定客户端与服务端建立连接后发送 request body 的超时时间。如果客户端在指定时间内没有发送任
何内容,Nginx 返回 HTTP 408(Request Timed Out)。

6、更改进程数

----------------更改进程数-------------------
在高并发场景,需要启动更多的Nginx进程以保证快速响应,以处理用户的请求,避免造成阻塞​
cat /proc/cpuinfo | grep -c "physical id"      #查看cpu核数
ps aux | grep nginx                            #查看nginx主进程中包含几个子进程
​vim /usr/local/nginx/conf/nginx.confworker_processes 2;  #修改为核数相同或者2倍
worker_cpu_affinity 01 10; #设置每个进程由不同cpu处理,进程数配为4时0001 0010 0100 1000​
systemctl restart nginx

7、配置网页压缩                                                                                      

----------------配置网页压缩-------------------
Nginx的ngx_http_gzip_module压缩模块提供对文件内容压缩的功能
允许Nginx服务器将输出内容在发送客户端之前进行压缩,以节约网站带宽,提升用户的访问体验,默认
已经安装
可在配置文件中加入相应的压缩功能参数对压缩性能进行优化

vim /usr/local/nginx/conf/nginx.conf
http {
...... 
   gzip on;							#取消注释,开启gzip压缩功能
   gzip_min_length 1k;      		#最小压缩文件大小
   gzip_buffers 4 64k;      		#压缩缓冲区,大小为4个64k缓冲区
   gzip_http_version 1.1;   		#压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
   gzip_comp_level 6;       		#压缩比率      1:压缩比最小,速度最快;9:压缩比最
                                    大,传输速度最快,但处理也最慢,也比较的消耗CPU资源 
   gzip_vary on;					#支持前端缓存服务器存储压缩页面
   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;	
                                               #压缩类型,表示哪些网页文档启用压缩功能
...... 
}

cd /usr/local/nginx/html
先将game.jpg文件传到/usr/local/nginx/html目录下
vim index.html
...... 
<img src="game.jpg"/>				#网页中插入图片
</body>
</html>

systemctl restart nginx

在Linux系统中,打开火狐浏览器,右击点查看元素
选择 网络 ---> 选择 HTML、WS、其他 
访问 http://192.168.17.155 ,双击200响应消息查看响应头中包含 Content-Encoding: gzip

8、配置防盗链

    Web源主机:192.168.17.155
    盗链网站主机:192.168.17.156

     Web源主机配置:
----------------配置防盗链-------------------
vim /usr/local/nginx/conf/nginx.conf
http {
......
	server {
	......
		location ~* \.(jpg|gif|swf)$ {
			valid_referers none blocked *.yjs0805.com yjs0805.com;
			if ( $invalid_referer ) {
				rewrite ^/ http://www.yjs0805.com/error.png;
				#return 403;
            }
        } 
	......
	}
}
-----------------------------------------------------------------------------
~* \.(jpg|gif|swf)$ :这段正则表达式表示匹配不区分大小写,以.jpg 或.gif 或.swf 结尾的
文件;valid_referers :设置信任的网站,可以正常使用图片;
none:允许没有http_refer的请求访问资源(根据Referer的定义,它的作用是指示一个请求是从哪
里链接过来的,如果直接在浏览器的地址栏中输入一个资源的URL地址,那么这种请求是不会包含 
Referer 字段的),如 http://www.yjs0805.com/game.jpg
我们使用 http://www.kgc.com 访问显示的图片,可以理解成 http://www.yjs0805.com/game.jpg 
这个请求是从 http://www.yjs0805.com 这个链接过来的。
blocked:允许不是http://开头的,不带协议的请求访问资源; 
*.yjs0805.com:只允许来自指定域名的请求访问资源,如 http://www.yjs0805.com

if语句:如果链接的来源域名不在valid_referers所列出的列表中,$invalid_referer为true,则
执行后面的操作,即进行重写或返回 403 页面。
---------------------------------------------------------------------------------

网页准备:
Web源主机(192.168.17.155)配置:
cd /usr/local/nginx/html
将game.jpg、error.png文件传到/usr/local/nginx/html目录下
vim index.html
<html>
<body>
<img src="game.jpg"/>
</body>
</html>

echo "192.168.17.155 www.yjs0805.com" >> /etc/hosts 
echo "192.168.17.156 www.zx0805.com" >> /etc/hosts 

盗链网站主机(192.168.17.156):
cd /usr/local/nginx/html
vim index.html

<html>
<body>
<img src="http://www.yjs0805.com/game.jpg"/>
</body>
</html>

echo "192.168.17.155 www.yjs0805.com" >> /etc/hosts 
echo "192.168.17.156 www.zx0805.com" >> /etc/hosts 

在盗图网站主机上进行浏览器验证
http://www.zx0805.com



9、Nginx SSL/TLS配置

9.1 创建自签名证书(仅用于测试环境)

如果您只是在开发或测试环境中使用 SSL,可以生成自签名证书。请按照以下步骤生成并配置自签名证书。

9.2 生成自签名证书

1.生成密钥文件和证书签名请求(CSR):

mkdir -p /usr/local/nginx/ssl/private
mkdir -p /usr/local/nginx/ssl/certs

#生成私钥文件
openssl genpkey -algorithm RSA -out /usr/local/nginx/ssl/private/nginx-
selfsigned.key -pkeyopt rsa_keygen_bits:2048
#生成csr文件
openssl req -new -key /usr/local/nginx/ssl/private/nginx-selfsigned.key -out
/usr/local/nginx/ssl/certs/nginx-selfsigned.csr


其他字段说明(一般在用 openssl req -new -key ... 生成 CSR 时会问)

    Country Name (2 letter code): 国家代码(必须 2 位,例如 CN、US)

    State or Province Name: 省/州全名,例如 Beijing

    Locality Name: 城市,例如 Beijing

    Organization Name: 公司或组织名,例如 MyCompany Ltd

    Organizational Unit Name: 部门名,例如 IT Department(可留空)

    Common Name (e.g. server FQDN): 你的域名,例如 example.com

    Email Address: 邮箱地址,例如 admin@example.com

2.生成自签名证书:
openssl x509 -req -days 365 -in  /usr/local/nginx/ssl/certs/nginx-selfsigned.csr 
-signkey  /usr/local/nginx/ssl/private/nginx-selfsigned.key -out  /usr/local
/nginx/ssl/certs/nginx-selfsigned.crt

3.验证证书生成是否成功:
证书应该已经保存在  /usr/local/nginx/ssl/certs/nginx-selfsigned.crt,
密钥文件保存在  /usr/local/nginx/ssl/private/nginx-selfsigned.key。

9.3配置Nginx启用SSL/TLS

vim  /usr/local/nginx/conf/nginx.conf

server {
    listen 443 ssl;
    server_name benet.com www.benet.com;

    ssl_certificate /usr/local/nginx/ssl/certs/nginx-selfsigned.crt;
    ssl_certificate_key /usr/local/nginx/ssl/private/nginx-selfsigned.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:TLS_AES_128_GCM_SHA256:
    TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256";
    ssl_prefer_server_ciphers on;

    location / {
        root /usr/share/nginx/html;
        index index.html;
    }
}

解释:

listen 443 ssl:告诉 Nginx 监听 HTTPS(端口 443)。
ssl_certificate和ssl_certificate_key:指定 SSL 证书和密钥的路径。
ssl_protocols TLSv1.2 TLSv1.3:只启用 TLS 1.2 和 TLS 1.3,禁用 SSL 和 TLS 1.0/1.1。
ssl_ciphers:定义加密套件。可以根据安全需求选择合适的加密方法。
ssl_prefer_server_ciphers on:强制服务器优先选择加密套件。


网站公告

今日签到

点亮在社区的每一天
去签到