nginx网络的优化

一 :隐藏版本号

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

curl -I http://192.168.23.103

img

 

返回目录

1.1 方法一修改配置文件方式

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

img

 

 

二、修改用户与组

vim /usr/local/nginx/conf/nginx.conf user nginx nginx; #设置为 nginx 用户 nginx 组 systemctl restart nginx

img

img

img

img

 

 

三、缓存时间

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天 } ...... } } #location ~ 表示开启正则匹配 systemctl restart ngi

 


四、日志切割

vi /opt/fenge.sh #!/bin/bash # Filename: fenge.sh d=$(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-$d #移动并重命名日志文件 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

img

 

 

五、连接超时

HTTP有一个KeepAlive模式,它告诉web服务器在处理完一个请求后保持这个TCP连接的打开状态。若接收到来自客户端的其它请求,服务端会利用这个未被关闭的连接,而不需要再建立一个连接

KeepAlive 在一段时间内保持打开状态,它们会在这段时间内占用资源。占用过多就会影响性能

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
    指定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)。

image-20210815050844389

image-20210815051118361

 

 

六、更改进程数

cat /proc/cpuinfo | grep -c "physical id" #查看cpu核数 ps aux | grep nginx #查看nginx主进程中包含几个子进程 vim /usr/local/nginx/conf/nginx.conf worker_processes 2; #修改为核数相同或者2倍 worker_cpu_affinity 01 10; #设置每个进程由不同cpu处理,进程数配为4时0001 0010 0100 1000 systemctl restart nginx #如果没有开启超线程,则worker_processes 数量和 核数相同 #如果开启了超线程,则 worker_processes 可以设置为 核数 乘以 cpu核心数 #设置完软件支持并发连接后,还要设置 系统支持 ulimet -n 65535 #设置最大同时支持 65535连接

img

 

 

 

posted @ 2021-08-15 14:27  宇宙无敌宇航员  阅读(109)  评论(0)    收藏  举报