Nginx 配置优化

Posted by Sunday on 2017-04-14

1. 隐藏版本信息

1
2
3
4
vim /usr/local/nginx/conf/nginx.conf
http{
server_tokens off;
}

2. 更改Nginx默认用户

1
2
3
4
root@Debian:~# useradd nginx -s /sbin/nologin -M
root@Debian:~# grep "user" /usr/local/nginx/conf/nginx.conf
user nginx nginx;
定义user和工作group 进程使用的凭证。如果group省略,user则使用名称等于的组。

3. 优化worker进程个数

1
2
3
4
5
6
7
8
worker_processes 4 一般为CPU核数 或 CPU核数*2
lscpu
root@Debian:~# grep 'physical id' /proc/cpuinfo|sort -nr|uniq -c|wc -l #查看物理CPU颗数
1
root@Debian:~# grep 'core id' /proc/cpuinfo | sort -u | wc -l #查看单核心数量
4
root@Debian:~# grep "processor" /etc/cpuinfo|sort -nr|uniq -c|wc -l #逻辑核心数
4

4. CPU核数绑定

1
2
3
4
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
防止进程只在一个核心上运行也可以使用 taskset 命令
taskset -c 1,2,3 /application/nginx/sbin/nginx start

5. Nginx事件处理模型优化

1
2
3
4
5
选用epoll Linux2.6以上
events{
use epoll;
}
可以不指定事件处理模型,Nginx会自动选择最佳的事件处理模型

6. 调整进程最大连接数

1
2
3
4
events{
worker_connections 2048;
}
并发=worker_process * worker_connections

7. worker进程最大打开文件数

1
2
worker_rlimit_nofile 65535;
设置为ulimit -HSn结果

8. 开启高效文件传输模式

1
2
3
4
5
6
7
sendfile参数用于开启文件的高效传输模式,同时将tcp_nopush和tcp_nodelay两个指定设为on,可防止网络及磁盘I/O阻塞,提升Nginx工作效
率。3个参数配合使用
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
}

9. 设置连接超时

1
2
3
4
5
6
7
http {
keepalive_timeout 60; #设置客户端连接保持会话的超时时间
client_header_timeout 15; #读取客户端请求头数据超时时间,超时则返回“Request time out(408)”
clietn_body_timeout 15; #读取客户端请求主体超时时间
send_timeout 15; #指定客户端响应时间
}
#将无用的连接尽快设置为超时,可以保护服务器的系统资源(CPU、内存、磁盘)

10.优化服务器域名的bash表大小

1
2
3
设置存放域名(server names)的最大哈希表大小
server_names_hash_bucket_size size 512;
#默认是512KB 一般要看系统给出确切的值。这里一般是cpu L1的4-5

11. 设置请求 上传大小

1
2
3
client_header_buffer_size 32k; #设置读取客户端请求标头的缓冲区大小
large_client_header_buffers 4 32k; #设置读取客户端请求标头的最大值number和size缓冲区
client_max_body_size 300m; #设置上传大小(根据业务调整)

12. 开启gzip压缩

1
2
3
4
5
6
7
8
9
10
11
gzip on; #开启gzip压缩功能
gzip_buffers 4 16k;
#压缩缓冲区大小,表示申请4个单位为16K的内存作为压缩结果流缓存,默认是申请与原始是数据大小相同的内存空间来存储gzip压缩结果;
gzip_http_version 1.1;
#压缩版本(默认1.1 前端为squid2.5时使用1.0)用于设置识别HTTP协议版本,默认是1.1,目前大部分浏览器已经支持GZIP压缩,使用默认即可。
gzip_comp_level 2;
#压缩比率,用来指定GZIP压缩比,1压缩比最小,处理速度最快;9压缩比最大,传输速度快,但处理最慢,也消耗CPU资源
gzip_types text/plain application/x-javascript text/css application/xml;
#用来指定压缩的类型,“text/html”类型总是会被压缩,这个就是HTTP原理部分讲的媒体类型。
gzip_vary on;
#vary hear支持,该选项可以让前端的缓存服务器缓存经过GZIP压缩的页面,例如用缓存经过Nginx压缩的数据

13. Nginx Fastcgi相关参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
http {
fastcgi_connect_timeout 300; #连接到后端fastcgi的超时时间
fastcgi_send_timeout 300; #已经和fastcgi建立连接后多久不传送数据,就会被断开
fastcgi_read_timeout 300; #接收fastcgi应答的超时时间
fastcgi_buffer_size 64k; 指定读取FastCGI服务端收到的第一部分响应信息的缓冲区大小
fastcgi_buffers 4 64k; 指定读取从FastCGI服务端收到的响应信息的缓冲区大小以及缓冲区数量
fastcgi_busy_buffers_size 128k #繁忙时的buffer,可以是fastcgi_buffer的两倍;
fastcgi_temp_file_write_size 128k; #fastcgi临时文件的大小,可设置128-256k
fastcgi_temp_path /data/ngx_fcgi_tmp; #fastcgi临时文件目录
fastcgi_cache_path /data/ngx_fcgi_cache levels=2:2 keys_zone=ngx_fcgi_cache:512m inactive=1d max_s
ize=40g; #缓存目录,可以设置目录哈希层级。比如2:2会生成256*256个子目录,keys_zene是这个缓存空间的名字,
cache是用多少内存(这样热门的内容nginx直接放入内存,提高访问速度),inactive表示默认失效时间,max_size表示
最多用多少硬盘空间,需要注意的是fastcgi_cache缓存是先卸载fastcgi_temp_path再移到fastcgi_cache_path。
所以这两个目录最好在同一个分区
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server {
location ~ .*\.(php|php5)?$ {
root html/www;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
fastcgi_cache ngx_fcgi_cache;#表示开启缓存并为其指定一个名称,可以有效降低cpu的负载,并且防止502的发生,但是也可能会带来其他问题
fastcgi_cache_valid 200 302 1h; #将对应的应答码缓存时间
fastcgi_cache_valid 301 1d; #将301缓存1天
fastcgi_cache_valid any 1m; #将其他应答缓存1分钟
fastcgi_cache_min_uses 1; #请求数量
fastcgi_cache_use_stale error timeout invalid_header http_500; #错误判断
fastcgi_cache_key http://$host$request_uri;
}
}

14. 配置Nginx expires缓存功能

1
2
3
4
5
6
7
8
server {
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { #指定缓存文件的类型
expires 365d; #指定缓存时间
}
location ~ .*\.(js|css)?$ {
expires 3d;
}
}

15.Nginx日志相关优化与安全

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1)每天进行日志切割,备份

#!/bin/sh
cd /application/nginx/logs/
mv www_access.log www.access_$(date +%F -d -1day).log
mv blog_access.log blog.access_$(date +%F -d -1day).log
/application/nginx/sbin/nginx -s reload

cat <</var/spool/cron/root>>EOF
00 00 * * * /bin/sh /server/scripts/cut_nginx_log.sh &gt;/dev/null 2&gt;&amp;1
EOF

2)不记录不需要的访问日志
对于健康检查或者某些图片、JS、CSS日志,一般不需要记录日志,因为在统计PV时是按照页面计算的,而且写入频繁会消耗IO,降低服务器性能
location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$ {
access_log off;
}
3)访问日志的权限设置
chown -R root.root /application/nginx/logs
chmod -R 700 /application/logs

16.Nginx站点目录及文件URL访问控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
1)根据扩展名限制程序或者文件被访问
资源文件夹如用户上传的头像,防止恶意上传脚本病毒文件被解析执行
server {
location ~ ^/images/.*\.(php|php5|sh|pl|py)$ { #指定目录限制访问
deny all;
}
location ~ ^/static/.*\.(php|php5|sh|pl|py)$ {
deny all;
}
location ~ ^/data/.*\.(php|php5|sh|pl|py)$ {
deny all;
}
location ~ .*\.(php|php5)?$ { #必须配置在解析之前
root html/www;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
}

2)禁止访问目录并返回指定HTTP代码

server {
location /admin/ { return 404; }
}
3)限制网站来源IP

server {
location ~ ^/admin/ {
allow 202.111.12.211;
#allow 192.168.1.0/24; #也可以限制IP段
deny all;
}
}
企业问题案列:Nginx做方向代理的时候可以限制客户端IP吗?
方法一:用if来控制
if ( $remotea_addr = 10.0.0.110 ) {
return 403;
}
if ( $remotea_addr = 10.0.0.111 ) {
set $allow_access_root 'true';
}
方法二:利用deny和allow
location / {
root html/blog;
index index.php index.html index.html;
deny 10.0.0.7;
allow all;
}

17.防止恶意解析访问企业网站

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
方法一
server {
listen 80 default_server;
server_name _;
return 501;
}

方法二
server {
listen 80 default_server;
server_name _;
rewrite ^(.*) http://www.sundayle.com$1 permanent;
}

方法三
server {
if ($host !~ ^www/.sundayle/.com$) {
rewrite ^(.*) http://www.sundayle.com$1 permanent;
}

18.Nginx图片及目录防盗链

1
2
3
4
5
6
7
8
9
网站图片被盗链最直接的影响就是网络带宽占用加大了,宽带费用变高了,网络流量忽高忽低
利用referer防盗链

location ~.* \.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
valid_referers none blocked *.sundayle.cn sundayle.cn;
if ($invalid_referer) {s
rewrite ^/ http://www.sundayle.cn/img/nolink.jpg
}
}

19. Nginx错误页面的优雅显示

1
2
3
server {
error_page 403 /403.html; #当出现403错误时,会跳转到403.html页面
}

20. Nginx防爬虫优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
robots.txt机器人协议
网络爬虫排除标准,告诉搜索引擎哪些目录可以抓取,哪些禁止抓取
禁止下载协议代理

if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
return 403;
}
防止N多爬虫代理访问网站
if ($http_user_agent ~*
“qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Yahoo! Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot”) {
return 403;
}
禁止不同浏览器访问
if ($http_user_agent ~* “Firefox|MSIE”)
{
rewrite ^(.*) http://blog.etiantian.org/$1 permanent
}

21. 限制HTTP请求方法

1
2
3
4
5
6
7
8
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 501;
}
只允许GET等,允许DELETE、SEARCH等
为防止黑客通过上传服务器执行木马,也可以在上传服务器上做限制HTTP的GET
if ($request_method ~* ^(GET)$ ) {
return 501;
}

22. 防DOS攻击

1
2
3
4
5
6
7
8
9
使用limit_conn_zone进行控制,控制单个IP或域名的访问次数,限制连续访问

limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_remote_addr zone=perserver:10m;
server {
limit_conn perip 10; 允许每一个IP地址最多同时打开有10个连接。
limit_conn perserver 100;
}
#还可以使用limit_req_zone进行控制,控制单个IP的访问速率

23. 使用CDN为网站内容加速

1
2
 CDN是一套全国或全球的分布式缓存集群,其实质是通过智能DNS判断用户的来源地域以及上网线路,为用户选择一个最接近用户地狱以及和用户上网线路相同的服务器节点,因为地狱近,切线路相同,所以,可以大幅度提升浏览网站的体验。
提升企业网站的用户访问体验。 可以阻挡大部分流量攻击,DOSS攻击

24. Nginx程序架构优化

1
2
3
4
5
解耦,一堆程序代码按照业务用途分开,然后提供服务,例如:注册登录、上传、下载、浏览列表、商品内容、订单支付等都应该是独立的程序服务,
只不过在客户端看来是一个整体而已,小公司最起码要做到的解耦是
01.网页页面服务
02.图片附件及下载服务
03.上传图片服务

另一个维度来总结

一、安全方面

  • 1.1. 根据实际情况,隐藏 nginx header 版本号
  • 1.2. 根据实际情况,更改源码,隐藏 nginx 软件名称
  • 1.3. 更改 nginx 默认用户及用户组
  • 1.4. nginx 站点目录及文件 URL 访问控制(防止恶意解析)
  • 1.5. 防止恶意解析访问企业网站
  • 1.6. 配置 nginx 图片及目录防盗链
  • 1.7. 配置 nginx 防爬虫
  • 1.8. 限制 HTTP 请求方法
  • 1.9. 防 DOS 攻击

    二、性能方面

  • 2.1. 根据 CPU 逻辑核心数,配置 nginx worker 进程个数
  • 2.2. 配置 nginx worker 进程的 CPU 亲和力参数
  • 2.3. 配置 ngixn worker 单个进程允许的客户端最大连接数
  • 2.4. 配置 nginx worker 进程的最大打开文件数
  • 2.5. 配置 nginx 事件处理模型为 epoll

    三、HTTP 协议方面

  • 3.1. 开启高效的文件传输模式(sendfile/tcp_nopush/tcp_nodelay)
  • 3.2. 设置连接超时时间
  • 3.3. 设置客户端上传文件大小
  • 3.4. fastcgi 调优

    四、功能方面

  • 4.1. 配置 nginx gzip 压缩功能
  • 4.2. 配置 nginx expires 缓存功能
  • 4.3. 配置 nginx 错误页面的优雅显示

    五、日志方面

  • 5.1. 每天进行日志切割、备份/不记录不需要的访问日志/访问日志的权限设置

    六、架构方面

  • 6.1. nginx 程序架构优化(服务解耦)
  • 6.2. 使用 CDN 为网站内容加速
    参考链接:
    https://jaminzhang.github.io/nginx/Nginx-Optimization-Summary/
    http://www.lichengbing.com/archivers/279.html