nginx性能优化

本文详细介绍Nginx服务器的全面性能优化策略,包括隐藏版本信息、调整工作进程数、优化事件模型、设置连接超时及文件上传限制、启用GZIP压缩、配置Expires缓存、防御网络爬虫等关键步骤,旨在提升网站响应速度与安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、隐藏nginx的版本号

1.查看版本信息

[root@lnmp ~]# curl -I 10.0.0.130   
HTTP/1.1 200 OK
Server: nginx/1.6.2 ###版本号显示
Date: Tue, 07 Aug 2018 00:52:49 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.3.27

2.编辑配置文件

[root@lnmp ~]# vi /application/nginx/conf/nginx.conf
5 http {
      6     server_tokens off;增加这一行,不添加默认为on
      ...
      ..
      .
    }

3.检查语法,重启服务

[root@lnmp ~]# nginx -t
nginx: the configuration file /usr/local/nginx-1.6.2/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx-1.6.2/conf/nginx.conf test is successful
[root@lnmp ~]# nginx -s reload

4.测试

[root@lnmp ~]# curl -I 10.0.0.130
HTTP/1.1 200 OK
Server: nginx ###版本号已经隐藏
Date: Tue, 07 Aug 2018 00:57:29 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.3.27

二、更改nginx默认用户与组

1.查看默认用户与组

[root@lnmp ~]# grep "#user" /application/nginx/conf/nginx.conf.default 
#user  nobody;

2.修改的两种方法

2.1编译时修改

[root@lnmp nginx-1.6.2]# ./configure --user=nginx --group=nginx ...

2.2修改配置文件

[root@lnmp nginx-1.6.2]# useradd nginx01 -s /sbin/nologin -M
[root@lnmp nginx-1.6.2]# egrep "user" /application/nginx/conf/nginx.conf         
user  nginx01;
[root@lnmp nginx-1.6.2]# ps -ef|grep nginx01
nginx01   56998  56721  0 21:18 ?        00:00:00 nginx: worker process

三、配置nginx worker进程个数

  • worker进程类似于饭店的服务员个数,当客户多的时候,服务员人数少,服务质量会差。相反,如果服务员人数多,客户少,成本会高。worker进程一般=CPU的个数或者=cpu*2

1.查看配置

[root@lnmp ~]# grep "worker_pro" /application/nginx/conf/nginx.conf  
worker_processes  1;###默认为1

四、根据cpu核数进行线程优化

  • 默认情况下,nginx多个进程可能更多的跑在一颗cpu上。

1.不同cpu对应的配置

例:四核CPU服务器
worker_cpu_affinity 0001 0010 0100 1000;
#这里0001 0010 0100 1000 是掩码,分别代表第1.2.3.4颗cpu核心。
[root@lnmp ~]# vi /application/nginx/conf/nginx.conf  
worker_processes  4;#修改数量
worker_cpu_affinity 0001 0010 0100 1000;#添加

五、事件处理模型优化

  • nginx的连接处理机制在于不同的操作系统采用不同的IO模型,在Linux使用epoll的
    IO多路复用模型,在window使用的是icop等。

1.编辑配置文件

[root@lnmp ~]# vi /application/nginx/conf/nginx.conf
events { 
    use epoll;###添加 
}
===》use是个事件模块指令,用来指定nginx的工作模式,nginx支持的工作模式有 select、poll、
kqueue、epoll、rtsig和/dev/poll;其中select和poll都是标准的工作模式,kqueue和epoll是高效
的工作模式,不通的是epoll用在Linux平台上,而kqueue用在BSD系统中。

六、调整单个进程允许的客户端最大连接数

1.编辑配置文件

[root@lnmp ~]# vi /application/nginx/conf/nginx.conf
events { 
    worker_connections  1024; 
}
===》worker_connections也是个事件模块指令,用于定义nginx每个进程最大连接数,默认是1024
最大客户端连接数有worker_precesses和worker_connections决定,进程的最大连接数受Linux系统
进程的最大打开文件数限制。

七、配置每个进程最大文件打开数

1.编辑配置文件

[root@lnmp ~]# vi /application/nginx/conf/nginx.conf
events { 
    worker_rlimit_nofile 65535; 
}

八、设置连接超时时间

vi  /application/nginx/conf/nginx.conf
http{
keepalive_timeout  65;###设置客户端连接保持会话的超时时间,超过这个时间,服务器会关闭连接
tcp_nodely ib; 
client_header_timeout 15;###设置客户端请求头读取超时时间,如超过这个时间,客户端没有发送任何数据,
                            nginx将返回“request timeout (408)”
client_body_timeout 15;###设置客户端请求主体读取超时时间,如超过这个时间,客户端没有发送任何数据,
}                       nginx将返回“request timeout (408)”,默认值是60

九、上传文件大小限制

client_max_body_size 10m;###默认为1m,超出会报413错误
context: http,server,location###可以填写到的模块

十、fastcgi调优

fastcgi_connect_timeout 300;
===》指定连接到后端fastcgi的超时时间
fastcgi_send_timeout 300;
===》向fastcgi1传送请求的超时时间,这个值是指已经完成了两次握手后向fastcgi传送请求的超时时间
fastcgi_read_timeout 300;
===》指定接收fastcgi应答的超时时间,这个值是指已经完成了两次握手后接收fastcgi应答的超时时间
fastcgi_buffer_size 64k;
===》 指定读取fastcgi应答第一部分需要用多大缓冲区,这个值表示将使用164kb的缓冲区读取应答的第一部分
(应答头)

十一、隐藏服务软件名信息

1.修改源码(三个文件)

[root@lnmp ~]# vi nginx-1.6.2/src/core/nginx.h 
     13 #define NGINX_VERSION      "8.8.8"
     14 #define NGINX_VER          "liang/" NGINX_VERSION
     16 #define NGINX_VAR          "liang"
[root@lnmp ~]# vi nginx-1.6.2/src/http/ngx_http_header_filter_module.c +48
     49 #static char ngx_http_server_string[] = "Server: nginx" CRLF;
     50 static char ngx_http_server_string[] = "Server: liang" CRLF;
[root@lnmp ~]# vi nginx-1.6.2/src/http/ngx_http_special_response.c      
     28 static u_char ngx_http_error_tail[] =
     29 #"<hr><center>nginx</center>" CRLF
     30 "<hr><center>liang</center>" CRLF

2.查看编译的参数

[root@lnmp ~]# nginx -V 
nginx version: nginx/1.6.2
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-23) (GCC) 
TLS SNI support enabled
configure arguments: --user=nginx --group=nginx --prefix=/usr/local/nginx-1.6.2 --with-http_stub_status_module --with-http_ssl_module

3.重新编译

[root@lnmp ~]# cd nginx-1.6.2
[root@lnmp nginx-1.6.2]# ./configure --user=nginx --group=nginx --prefix=/usr/local/nginx-1.6.2 --with-http_stub_status_module --with-http_ssl_module
[root@lnmp nginx-1.6.2]# make && make install

十二、配置nginx gzip压缩功能

1.对应的参数说明

官方帮助文档:链接

gzip on;
===》开启gzip压缩功能
gzip_min_length 1k;
===》设置允许压缩的页面最小字节数,页面字节数从header头的content-length中获取。
默认值是0,不管页面多大都进行压缩。
gzip_buffers 4 16k;
===》压缩缓冲区大小;表示申请四个单位为16k的内存座位压缩结果流缓存,默认值是申请
与原始数据大小相同的内存空间来存储gzip压缩结果。
gzip_comp_level 2;
===》压缩比率。用来指定gzip压缩比,1最小,处理速度最快,9最大,传输速度快,但处理慢
gzip_types text/css text/xml application/x-javascript
===》用来指定压缩的类型(查看所有类型cat conf/mime.types   )
gzip——vary on;
===》该选项可以让前端的缓存服务器缓存经过gzip压缩的页面

2.完整的配置

gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 9;
gzip_types  text/css text/xml application/x-javascript
gzip——vary on;

十三、配置expires缓存功能

功能优点:
    可以降低网站购买的带宽,节约成本,减轻服务器压力,同时提升了用户访问体验。
功能缺点:
    被缓存的页面或数据更新了,用户看到的可能还是旧的内容,反而影响用户体验。
1.配置
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)${##类型
    expires     3650d;###缓存的天数
    root    html/bbs#指定目录

}
location ~ .*\.(js|css)?${
    expires     30d;
    root    html/bbs
}

location ~ ^/(bbs|www/blog)/{#匹配多个目录
    expires 30d;
}

十四、防网络爬虫

1.robots.txt介绍与配置

搜索引擎使用spider程序自动访问互联网上的网页并获取网页信息。spider在访问一个网站时,会首先会检查该网站的根域下是否有一个叫做robots.txt的纯文本文件。您可以在您的网站中创建一个纯文本文件robots.txt,
在文件中声明该网站中不想被robot访问的部分或者指定搜索引擎只收录特定的部分。
    请注意,仅当您的网站包含不希望被搜索引擎收录的内容时,
才需要使用robots.txt文件。如果您希望搜索引擎收录网站上所有内容,
请勿建立robots.txt文件或者创建一个内容为空的robots.txt文件。
robots.txt文件应该放置在网站根目录下
1.仅禁止Baiduspider访问您的网站

User-agent: Baiduspider

Disallow: /
2.允许所有的robot访问
User-agent: * 
Allow: /

2.nginx.conf中配置

上述的robots.txt只是一种规范,其实不能真正禁止爬虫,只是告诉别人不给爬,实际上别人
可以忽视的robots设置。想要真正的禁止需要在nginx.conf下配置
server{
if ($http_user_agent ~* "qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Feedfetcher-Google|Yahoo! Slurp|Yahoo! Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot|ia_archiver|Tomato Bot")#这里可以写浏览器的名称,表示禁用某些浏览器的访问 
{ 
return 403; 
    } 
}

十五、日志切割

    nginx的日志默认是不自动切割的,所有的内容都会往一个日志文件写,这样会导致文件空间越来越大,需要手动编写脚本切割。
1.日志配置
http{  
   log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                       '"$http_user_agent" "$http_x_forwarded_for"';
    server{
        access_log logs/access_www_log main;
        error_log logs/error_www_log error;
    }
}
2.编辑脚本按天切割
[root@nginx ~]# cat /server/scritp/ngins_log.sh 
#!/bin/bash
Dir=/application/nginx/logs/#日志目录
File=access_www_log
cd ${Dir}
[ -f $File ]&&{
mv $File $(date +%F -d -1day)_$File#修改文件名字
/application/nginx/sbin/nginx -s reload#重启生成新的日志
}
[root@nginx ~]# crontab -l#每天0点定时执行脚本
#cut nginx access log
00 00 * * * /bin/bash /server/scritp/ngins_log.sh >/dev/null 2>&1

十六、不记录不需要的日志

    对于健康检查或某些图片的日志,一般不需要记录,因为在统计PV时是按照页面计算
而且日志写入频繁会消耗IO,降低服务性能。
1.配置
server{
location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIf)${
        access_log off;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值