Nginx的优化与防盗链

系统 Linux 系统运维
由于Nginx本身的一些优点,轻量,开源,易用,越来越多的公司使用nginx作为自己公司的web应用服务器,本文详细介绍nginx源码安装的同时并对nginx进行优化配置。

Nginx是俄罗斯人编写的十分轻量级的HTTP服务器,Nginx,它的发音为“engine X”,是一个高性能的HTTP和反向代理服务器,同时也是一个IMAP/POP3/SMTP 代理服务器.Nginx是由俄罗斯人Igor Sysoev为俄罗斯访问量第二的Rambler.ru站点开发.

Nginx以事件驱动(epoll)的方式编写,所以有非常好的性能,同时也是一个非常高效的反向代理、负载平衡。但是Nginx并不支持cgi方式运行,原因是可以减少因此带来的一些程序上的漏洞。所以必须使用FastCGI方式来执行PHP程序。

由于Nginx本身的一些优点,轻量,开源,易用,越来越多的公司使用nginx作为自己公司的web应用服务器,本文详细介绍nginx源码安装的同时并对nginx进行优化配置。

一、Nginx的优化

1、编译安装前优化

编译前的优化主要是用来修改程序名等等,目的更改源码隐藏软件名称和版本号

安装zlib-devel、pcre-devel等依赖包 

  1. [root@localhost ~]# yum -y install gcc gcc-c++ make libtool zlib zlib-devel pcre pcre-devel openssl openssl-devel 

下载nginx的源码包:http://nginx.org/download

解压源码包:

  1. [root@localhost ~]# tar zxf nginx-1.10.2.tar.gz 
  2. [root@localhost ~]# cd nginx-1.10.2/  

隐藏软件名称和版本号

  1. [root@localhost nginx-1.10.2]# vi src/core/nginx.h 

隐藏软件名称和版本号 

  1. #defineNGINX_VERSION      "1.10.2"    //第13行 
  2.  
  3. //此行修改的是你想修改的软件名称 
  4.      
  5. #defineNGINX_VER          "nginx/" NGINX_VERSION  //第14行  

修改上面的信息,即可更改nginx显示版本。例如:

  1. #define NGINX_VERSION      "7.0" 
  2. #defineNGINX_VER          "IIS/" NGINX_VERSION  

修改HTTP头信息中的connection字段,防止回显具体版本号

拓展:通用http头,通用头包含请求和响应消息都支持的头,通用头包含Cache-Control、 Connection、Date、Pragma、Transfer-Encoding、Upgrade、Via。对通用头的扩展要求通讯双方都支持此扩展,如果存在不支持的通用头,一般将会作为实体头处理。那么也就是说有部分设备,或者是软件,能获取到connection,部分不能,要隐藏就要彻底!

  1. [root@localhost nginx-1.10.2]# vi src/http/ngx_http_header_filter_module.c 

修改前:

  1. static char ngx_http_server_string[] ="Server: nginx" CRLF;  //第49行 

修改后:

  1. staticchar ngx_http_server_string[] = "Server: IIS"CRLF 

定义了http错误码的返回

有时候我们页面程序出现错误,Nginx会代我们返回相应的错误代码,回显的时候,会带上nginx和版本号,我们把他隐藏起来

  1. [root@localhost nginx-1.10.2]# vi src/http/ngx_http_special_response.c 

修改前

  1. static u_char ngx_http_error_tail[] =     //第29行 
  2. "<hr><center>nginx</center>" CRLF 
  3. "</body>" CRLF 
  4. "</html>" CRLF 

修改后

  1. static u_char ngx_http_error_tail[] = 
  2. "<hr><center>IIS</center>" CRLF 
  3. "</body>" CRLF 
  4. "</html>" CRLF 
  5.  

2、安装ngnix

  1. [root@localhost ~]# groupadd www    #添加www组 
  2. [root@localhost ~]# useradd -g www www -s /sbin/nologin    #创建nginx运行账户www并加入到www组,不允许www用户直接登录系统 
  3. [root@localhost nginx-1.10.2]# ./configure --prefix=/usr/local/nginx1.10 --with-http_dav_module --with-http_stub_status_module --with-http_addition_module --with-http_sub_module --with-http_flv_module --with-http_mp4_module --with-pcre --with-http_ssl_module --with-http_gzip_static_module --user=www --group=www && make && make install 

 相关选项说明

--with-http_dav_module #增加PUT,DELETE,MKCOL:创建集合,COPY和MOVE方法

--with-http_stub_status_module #获取Nginx的状态统计信息

--with-http_addition_module #作为一个输出过滤器,支持不完全缓冲,分部分相应请求

--with-http_sub_module #允许一些其他文本替换Nginx相应中的一些文本

--with-http_flv_module #提供支持flv视频文件支持

--with-http_mp4_module #提供支持mp4视频文件支持,提供伪流媒体服务端支

--with-http_ssl_module #启用ngx_http_ssl_module

如果pcre是通过编译安装的话,例如

  1. # tar zxvf/usr/local/src/pcre-8.36.tar.gz -C /usr/local/src/ 
  2. # cd  /usr/local/src/pcre-8.36 
  3. # ./configure &&make && make install  

则--with-pcre=/usr/local/src/pcre-8.36 #需要注意,这里指的是源码,用#./configure --help | grep pcre查看帮助

  1. [root@localhost nginx-1.10.2]#ln-s /usr/local/nginx1.10/sbin/nginx /usr/local/sbin/ 
  2. [root@localhost nginx-1.10.2]#nginx-t  

启动nginx

  1. [root@localhost nginx-1.10.2]nginx 
  2. [root@localhost nginx-1.10.2]# netstat -anpt | grep nginx 
  3. tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      7424/nginx: master  

测试是否隐藏了版本和软件名

  1. [root@localhost nginx-1.10.2]# curl -I http://192.168.129.150 
  2. HTTP/1.1 200 OK 
  3. Server: IIS/7.0 
  4. Date: Sat, 18 Mar 2017 02:16:41 GMT 
  5. Content-Type: text/html 
  6. Content-Length: 612 
  7. Last-Modified: Sat, 18 Mar 2017 00:51:03 GMT 
  8. Connection: keep-alive 
  9. ETag: "58cc8477-264" 
  10. Accept-Ranges: bytes 
  11. [root@localhost nginx-1.10.2]# nginx -h 
  12. nginx version: IIS/7.0 
  13. Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives] 
  14.   
  15. Options: 
  16.   -?,-h         : this help 
  17.   -v            : show version and exit 
  18.   -V            : show version and configure options then exit 
  19.   -t            : test configuration and exit 
  20.   -T            : test configuration, dump it and exit 
  21.   -q            : suppress non-error messages during configuration testing 
  22.   -s signal     : send signal to a master process: stop, quit, reopen, reload 
  23.   -p prefix     : set prefix path (default: /usr/local/nginx1.10/) 
  24.   -c filename   : set configuration file (default: conf/nginx.conf) 
  25.   -g directives : set global directives out of configuration file

 

3、nginx配置项优化

  1. [root@localhost nginx-1.10.2]# ps -ef | grep nginx 
  2. root      7424     1  0 08:52 ?        00:00:00 nginx: master process nginx 
  3. www      34878  7424  0 10:20 ?        00:00:00 nginx: worker process  

在这里我们还可以看到在查看的时候,work进程是nginx程序用户,但是master进程还是root,其中,master是监控进程,也叫主进程,work是工作进程,部分还有cache相关进程,关系如图: 

 

 

 

可以直接理解为master是管理员,work进程才是为用户提供服务的!

(1):Nginx运行工作进程个数,一般我们设置CPU的核心或者核心数x2

如果不了解cpu的核数,可以top命令之后按1也可以看出来,也可以查看/proc/cpuinfo文件

  1. [root@localhost nginx-1.10.2]# grep ^processor /proc/cpuinfo | wc -l 
  2.   
  3. 2  
  4. [root@localhost ~]#vi /usr/local/nginx1.10/conf/nginx.conf 
  5.  worker_processes  4; 
  6. [root@localhost ~]#/usr/local/nginx1.10/sbin/nginx -s reload 
  7. [root@localhost ~]# ps -aux | grep nginx | grep -v grep 
  8.   
  9. root      7424  0.0  0.1 178828  3004 ?        Ss   08:52   0:00 nginx: master process nginx 
  10.   
  11. www      34878  0.0  1.5 207536 28880 ?        S    10:20   0:00 nginx: worker process 
  12.   
  13. www      34879  0.0  1.5 207536 28636 ?        S    10:20   0:00 nginx: worker process 
  14.   
  15. www      34880  0.0  1.5 207536 28636 ?        S    10:20   0:00 nginx: worker process 
  16.   
  17. www      34881  0.0  1.5 207536 28576 ?        S    10:20   0:00 nginx: worker process 
  18.   
  19. www      34882  0.0  0.1 180912  1908 ?        S    10:20   0:00 nginx: cache manager process  

Nginx运行CPU亲和力

比如4核配置

  1. worker_processes  4; 
  2.   
  3. worker_cpu_affinity 0001 0010 0100 1000;  

比如8核配置

  1. worker_processes 8; 
  2. worker_cpu_affinity 00000001 0000001000000100 00001000 00010000 00100000 01000000 10000000;  

worker_processes最多开启8个,8个以上性能提升不会再提升了,而且稳定性变得更低,所以8个进程够用了

Nginx最多可以打开文件数

  1. worker_rlimit_nofile 65535; 

这个指令是指当一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(ulimit -n)与nginx进程数相除,但是nginx分配请求并不是那么均匀,所以最好与ulimit -n的值保持一致。

注:文件资源限制的配置可以在/etc/security/limits.conf设置,针对root/user等各个用户或者*代表所有用户来设置。

  1. *     soft   nofile  65535 
  2. *    hard  nofile    65535  

用户重新登录生效(ulimit -n)

(2)Nginx事件处理模型

  1. events { 
  2. use epoll; 
  3. worker_connections 65535; 
  4. multi_accept on
  5.  

nginx采用epoll事件模型,处理效率高,work_connections是单个worker进程允许客户端最大连接数,这个数值一般根据服务器性能和内存来制定,实际最大值就是worker进程数乘以work_connections,实际我们填入一个65535,足够了,这些都算并发值,一个网站的并发达到这么大的数量,也算一个大站了!

multi_accept 告诉nginx收到一个新连接通知后接受尽可能多的连接,默认是on,设置为on后,多个worker按串行方式来处理连接,也就是一个连接只有一个worker被唤醒,其他的处于休眠状态,设置为off后,多个worker按并行方式来处理连接,也就是一个连接会唤醒所有的worker,直到连接分配完毕,没有取得连接的继续休眠。当你的服务器连接数不多时,开启这个参数会让负载有一定的降低,但是当服务器的吞吐量很大时,为了效率,可以关闭这个参数。

(3)开启高效传输模式

  1. http { 
  2. include mime.types; 
  3. default_type application/octet-stream; 
  4. …… 
  5. sendfile on
  6. tcp_nopush on
  7. ……  

Include mime.types; //媒体类型,include 只是一个在当前文件中包含另一个文件内容的指令

default_typeapplication/octet-stream; //默认媒体类型足够

sendfile on;//开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。

注意:如果图片显示不正常把这个改成off。

tcp_nopush on;必须在sendfile开启模式才有效,防止网路阻塞,积极的减少网络报文段的数量(将响应头和正文的开始部分一起发送,而不一个接一个的发送。)

(4)连接超时时间

主要目的是保护服务器资源,CPU,内存,控制连接数,因为建立连接也是需要消耗资源的

  1. keepalive_timeout 60; 
  2. tcp_nodelay on
  3. client_header_buffer_size 4k; 
  4. open_file_cache max=102400 inactive=20s; 
  5. open_file_cache_valid 30s; 
  6. open_file_cache_min_uses 1; 
  7. client_header_timeout 15; 
  8. client_body_timeout 15; 
  9. reset_timedout_connection on
  10. send_timeout 15; 
  11. server_tokens off
  12. client_max_body_size 10m;  

keepalived_timeout客户端连接保持会话超时时间,超过这个时间,服务器断开这个链接

tcp_nodelay;也是防止网络阻塞,不过要包涵在keepalived参数才有效

client_header_buffer_size4k;客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过 1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。分页大小可以用命令getconf PAGESIZE取得。

open_file_cache max=102400 inactive=20s;这个将为打开文件指定缓存,默认是没有启用的,max指定缓存数量,建议和打开文件数一致,inactive 是指经过多长时间文件没被请求后删除缓存。

open_file_cache_valid 30s;这个是指多长时间检查一次缓存的有效信息。

open_file_cache_min_uses 1;open_file_cache指令中的inactive 参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive 时间内一次没被使用,它将被移除。

client_header_timeout设置请求头的超时时间。我们也可以把这个设置低些,如果超过这个时间没有发送任何数据,nginx将返回request time out的错误

client_body_timeout设置请求体的超时时间。我们也可以把这个设置低些,超过这个时间没有发送任何数据,和上面一样的错误提示

reset_timeout_connection 告诉nginx关闭不响应的客户端连接。这将会释放那个客户端所占有的内存空间。

send_timeout响应客户端超时时间,这个超时时间仅限于两个活动之间的时间,如果超过这个时间,客户端没有任何活动,nginx关闭连接

server_tokens 并不会让nginx执行的速度更快,但它可以关闭在错误页面中的nginx版本数字,这样对于安全性是有好处的。client_max_body_size上传文件大小限制

(5)fastcgi调优

  1. fastcgi_connect_timeout 600; 
  2. fastcgi_send_timeout     600; 
  3. fastcgi_read_timeout     600; 
  4. fastcgi_buffer_size      64k; 
  5. fastcgi_buffers       4 64k; 
  6. fastcgi_busy_buffers_size     128k; 
  7. fastcgi_temp_file_write_size  128k; 
  8. fastcgi_temp_path   /usr/local/nginx1.10/nginx_tmp; 
  9. fastcgi_intercept_errors  on
  10. fastcgi_cache_path /usr/local/nginx1.10/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:128m inactive=1d max_size=10g; 

fastcgi_connect_timeout 600; #指定连接到后端FastCGI的超时时间。

fastcgi_send_timeout 600; #向FastCGI传送请求的超时时间。

fastcgi_read_timeout 600; #指定接收FastCGI应答的超时时间。

fastcgi_buffer_size 64k; #指定读取FastCGI应答第一部分需要用多大的缓冲区,默认的缓冲区大小为fastcgi_buffers指令中的每块大小,可以将这个值设置更小。

fastcgi_buffers 4 64k; #指定本地需要用多少和多大的缓冲区来缓冲FastCGI的应答请求,如果一个php脚本所产生的页面大小为256KB,那么会分配4个64KB的缓冲区来缓存,如果页面大小大于256KB,那么大于256KB的部分会缓存到fastcgi_temp_path指定的路径中,但是这并不是好方法,因为内存中的数据处理速度要快于磁盘。一般这个值应该为站点中php脚本所产生的页面大小的中间值,如果站点大部分脚本所产生的页面大小为256KB,那么可以把这个值设置为“8 32K”、“4 64k”等。

fastcgi_busy_buffers_size 128k; #建议设置为fastcgi_buffers的两倍,繁忙时候的buffer

fastcgi_temp_file_write_size 128k; #在写入fastcgi_temp_path时将用多大的数据块,默认值是fastcgi_buffers的两倍,该数值设置小时若负载上来时可能报502Bad Gateway

fastcgi_temp_path #缓存临时目录

fastcgi_intercept_errors on;#这个指令指定是否传递4xx和5xx错误信息到客户端,或者允许nginx使用error_page处理错误信息。

注:静态文件不存在会返回404页面,但是php页面则返回空白页!!

fastcgi_cache_path /usr/local/nginx1.10/fastcgi_cachelevels=1:2 keys_zone=cache_fastcgi:128minactive=1d max_size=10g;# fastcgi_cache缓存目录,可以设置目录层级,比如1:2会生成16*256个子目录,cache_fastcgi是这个缓存空间的名字,cache是用多少内存(这样热门的内容nginx直接放内存,提高访问速度),inactive表示默认失效时间,如果缓存数据在失效时间内没有被访问,将被删除,max_size表示最多用多少硬盘空间。

fastcgi_cache cache_fastcgi; #表示开启FastCGI缓存并为其指定一个名称。开启缓存非常有用,可以有效降低CPU的负载,并且防止502的错误放生。cache_fastcgi为proxy_cache_path指令创建的缓存区名称

fastcgi_cache_valid 200 302 1h; #用来指定应答代码的缓存时间,实例中的值表示将200和302应答缓存一小时,要和fastcgi_cache配合使用

fastcgi_cache_valid 301 1d; #将301应答缓存一天

fastcgi_cache_valid any 1m; #将其他应答缓存为1分钟

fastcgi_cache_min_uses 1; #该指令用于设置经过多少次请求的相同URL将被缓存。

fastcgi_cache_keyhttp://$host$request_uri; #该指令用来设置web缓存的Key值,nginx根据Key值md5哈希存储.一般根据$host(域名)、$request_uri(请求的路径)等变量组合成proxy_cache_key 。

fastcgi_pass #指定FastCGI服务器监听端口与地址,可以是本机或者其它

总结:

nginx的缓存功能有:proxy_cache /fastcgi_cache

proxy_cache的作用是缓存后端服务器的内容,可能是任何内容,包括静态的和动态。

fastcgi_cache的作用是缓存fastcgi生成的内容,很多情况是php生成的动态的内容。

proxy_cache缓存减少了nginx与后端通信的次数,节省了传输时间和后端宽带。

fastcgi_cache缓存减少了nginx与php的通信的次数,更减轻了php和数据库(mysql)的压力。

(6)gzip调优

使用gzip压缩功能,可能为我们节约带宽,加快传输速度,有更好的体验,也为我们节约成本,所以说这是一个重点。Nginx启用压缩功能需要你来ngx_http_gzip_module模块,apache使用的是mod_deflate一般我们需要压缩的内容有:文本,js,html,css,对于图片,视频,flash什么的不压缩,同时也要注意,我们使用gzip的功能是需要消耗CPU的!

  1. gzip on
  2. gzip_min_length  2k; 
  3. gzip_buffers    4 32k; 
  4. gzip_http_version 1.1; 
  5. gzip_comp_level   6; 
  6. gzip_types   text/plaintext/css text/javascript application/json application/javascriptapplication/x-javascript application/xml; 
  7. gzip_vary on
  8. gzip_proxied any 

gzip on; #开启压缩功能

gzip_min_length 1k; #设置允许压缩的页面最小字节数,页面字节数从header头的Content-Length中获取,默认值是0,不管页面多大都进行压缩,建议设置成大于1K,如果小与1K可能会越压越大。

gzip_buffers 4 32k; #压缩缓冲区大小,表示申请4个单位为32K的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。

gzip_http_version 1.1; #压缩版本,用于设置识别HTTP协议版本,默认是1.1,目前大部分浏览器已经支持GZIP解压,使用默认即可

gzip_comp_level 6; #压缩比例,用来指定GZIP压缩比,1压缩比最小,处理速度最快,9压缩比最大,传输速度快,但是处理慢,也比较消耗CPU资源。

gzip_types text/css text/xmlapplication/javascript; #用来指定压缩的类型,‘text/html’类型总是会被压缩。

默认值: gzip_types text/html (默认不对js/css文件进行压缩)

# 压缩类型,匹配MIME类型进行压缩

# 不能用通配符 text/*

# (无论是否指定)text/html默认已经压缩

# 设置哪压缩种文本文件可参考 conf/mime.types

gzip_vary on; #vary header支持,改选项可以让前端的缓存服务器缓存经过GZIP压缩的页面,例如用Squid缓存经过nginx压缩的数据

(7)expires缓存调优

缓存,主要针对于图片,css,js等元素更改机会比较少的情况下使用,特别是图片,占用带宽大,我们完全可以设置图片在浏览器本地缓存365d,css,js,html可以缓存个10来天,这样用户第一次打开加载慢一点,第二次,就非常快了!缓存的时候,我们需要将需要缓存的拓展名列出来, Expires缓存配置在server字段里面

  1. location ~*\.(ico|jpe?g|gif|png|bmp|swf|flv)$ { 
  2.   expires 30d; 
  3.   #log_not_found off
  4.   access_log off
  5.    
  6. location ~* \.(js|css)$ { 
  7.   expires 7d; 
  8.   log_not_found off
  9.   access_log off
  10.  

注:log_not_found off;是否在error_log中记录不存在的错误。默认是。

总结:

expire功能优点 (1)expires可以降低网站购买的带宽,节约成本(2)同时提升用户访问体验(3)减轻服务的压力,节约服务器成本,是web服务非常重要的功能。 expire功能缺点:被缓存的页面或数据更新了,用户看到的可能还是旧的内容,反而影响用户体验。解决办法:第一个缩短缓存时间,例如:1天,但不彻底,除非更新频率大于1天;第二个对缓存的对象改名。

网站不希望被缓存的内容 1)网站流量统计工具2)更新频繁的文件(google的logo)

(8)防盗链

防止别人直接从你网站引用图片等链接,消耗了你的资源和网络流量,那么我们的解决办法由几种: 1:水印,品牌宣传,你的带宽,服务器足够 2:防火墙,直接控制,前提是你知道IP来源 3:防盗链策略下面的方法是直接给予404的错误提示

  1. location ~*^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ { 
  2.     valid_referers none blocked www.benet.com benet.com; 
  3.     if ($invalid_referer) { 
  4.       #return 302 http://www.benet.com/img/nolink.jpg; 
  5.       return 404; 
  6.        break; 
  7.     } 
  8.     access_log off
  9.  }  

参数可以使如下形式:

none 意思是不存在的Referer头(表示空的,也就是直接访问,比如直接在浏览器打开一个图片)

blocked 意为根据防火墙伪装Referer头,如:“Referer: XXXXXXX”。

server_names 为一个或多个服务器的列表,0.5.33版本以后可以在名称中使用“*”通配符。

(9)内核参数优化

fs.file-max =999999:这个参数表示进程(比如一个worker进程)可以同时打开的最大句柄数,这个参数直线限制最大并发连接数,需根据实际情况配置。

net.ipv4.tcp_max_tw_buckets= 6000 #这个参数表示操作系统允许TIME_WAIT套接字数量的最大值,如果超过这个数字,TIME_WAIT套接字将立刻被清除并打印警告信息。该参数默认为180000,过多的TIME_WAIT套接字会使Web服务器变慢。

注:主动关闭连接的服务端会产生TIME_WAIT状态的连接

net.ipv4.ip_local_port_range = 1024 65000 #允许系统打开的端口范围。

net.ipv4.tcp_tw_recycle = 1#启用timewait快速回收。

net.ipv4.tcp_tw_reuse = 1#开启重用。允许将TIME-WAITsockets重新用于新的TCP连接。这对于服务器来说很有意义,因为服务器上总会有大量TIME-WAIT状态的连接。

net.ipv4.tcp_keepalive_time= 30:这个参数表示当keepalive启用时,TCP发送keepalive消息的频度。默认是2小时,若将其设置的小一些,可以更快地清理无效的连接。

net.ipv4.tcp_syncookies = 1#开启SYN Cookies,当出现SYN等待队列溢出时,启用cookies来处理。

net.core.somaxconn = 40960 #web 应用中 listen 函数的 backlog 默认会给我们内核参数的net.core.somaxconn 限制到128,而nginx定义的NGX_LISTEN_BACKLOG 默认为511,所以有必要调整这个值。

注:对于一个TCP连接,Server与Client需要通过三次握手来建立网络连接.当三次握手成功后,我们可以看到端口的状态由LISTEN转变为ESTABLISHED,接着这条链路上就可以开始传送数据了.每一个处于监听(Listen)状态的端口,都有自己的监听队列.监听队列的长度与如somaxconn参数和使用该端口的程序中listen()函数有关

somaxconn参数:定义了系统中每一个端口最大的监听队列的长度,这是个全局的参数,默认值为128,对于一个经常处理新连接的高负载 web服务环境来说,默认的 128 太小了。大多数环境这个值建议增加到 1024 或者更多。大的侦听队列对防止拒绝服务DoS 攻击也会有所帮助。

net.core.netdev_max_backlog = 262144 #每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。

net.ipv4.tcp_max_syn_backlog = 262144 #这个参数标示TCP三次握手建立阶段接受SYN请求队列的最大长度,默认为1024,将其设置得大一些可以使出现Nginx繁忙来不及accept新连接的情况时,Linux不至于丢失客户端发起的连接请求。

net.ipv4.tcp_rmem = 1024087380 12582912#这个参数定义了TCP接受缓存(用于TCP接受滑动窗口)的最小值、默认值、最大值。

net.ipv4.tcp_wmem = 10240 87380 12582912:这个参数定义了TCP发送缓存(用于TCP发送滑动窗口)的最小值、默认值、最大值。

net.core.rmem_default = 6291456:这个参数表示内核套接字接受缓存区默认的大小。

net.core.wmem_default = 6291456:这个参数表示内核套接字发送缓存区默认的大小。

net.core.rmem_max = 12582912:这个参数表示内核套接字接受缓存区的最大大小。

net.core.wmem_max = 12582912:这个参数表示内核套接字发送缓存区的最大大小。

net.ipv4.tcp_syncookies= 1:该参数与性能无关,用于解决TCP的SYN攻击。

下面贴一个完整的内核优化设置:

  1. fs.file-max = 999999 
  2. net.ipv4.ip_forward = 0 
  3. net.ipv4.conf.default.rp_filter = 1 
  4. net.ipv4.conf.default.accept_source_route= 0 
  5. kernel.sysrq = 0 
  6. kernel.core_uses_pid = 1 
  7. net.ipv4.tcp_syncookies = 1 
  8. kernel.msgmnb = 65536 
  9. kernel.msgmax = 65536 
  10. kernel.shmmax = 68719476736 
  11. kernel.shmall = 4294967296 
  12. net.ipv4.tcp_max_tw_buckets = 6000 
  13. net.ipv4.tcp_sack = 1 
  14. net.ipv4.tcp_window_scaling = 1 
  15. net.ipv4.tcp_rmem = 10240 87380 12582912 
  16. net.ipv4.tcp_wmem = 10240 87380 12582912 
  17. net.core.wmem_default = 8388608 
  18. net.core.rmem_default = 8388608 
  19. net.core.rmem_max = 16777216 
  20. net.core.wmem_max = 16777216 
  21. net.core.netdev_max_backlog = 262144 
  22. net.core.somaxconn = 40960 
  23. net.ipv4.tcp_max_orphans = 3276800 
  24. net.ipv4.tcp_max_syn_backlog = 262144 
  25. net.ipv4.tcp_timestamps = 0 
  26. net.ipv4.tcp_synack_retries = 1 
  27. net.ipv4.tcp_syn_retries = 1 
  28. net.ipv4.tcp_tw_recycle = 1 
  29. net.ipv4.tcp_tw_reuse = 1 
  30. net.ipv4.tcp_mem = 94500000 915000000 927000000 
  31. net.ipv4.tcp_fin_timeout = 1 
  32. net.ipv4.tcp_keepalive_time = 30 
  33. net.ipv4.ip_local_port_range= 1024 65000  

执行sysctl -p使内核修改生效

(10)关于系统连接数的优化:

linux 默认值 open files为1024

  1. [root@localhost ~]# ulimit -n  
  2.   
  3. 1024  

说明server只允许同时打开1024个文件

使用ulimit -a 可以查看当前系统的所有限制值,使用ulimit -n 可以查看当前的最大打开文件数。

新装的linux 默认只有1024 ,当作负载较大的服务器时,很容易遇到error: too many open files。因此,需要将其改大

在/etc/security/limits.conf最后增加:

  1. *                soft    nofile          65535 
  2. *                hard    nofile          65535 
  3. *                soft    noproc          65535 
  4. *                hard    noproc          65535  

二、部署LNMP

1、安装php

(1)解决依赖关系

  1. [root@localhost ~]#yum -y install libxml2-devel libcurl-devel openssl-devel bzip2-devel 

安装libmcrypt

  1. [root@localhost ~]#tar zxf libmcrypt-2.5.7.tar.gz 
  2. [root@localhost ~]# cd libmcrypt-2.5.7/ 
  3. [root@localhost libmcrypt-2.5.7]# ./configure --prefix=/usr/local/libmcrypt && make && make install  

(2)编译安装php

  1. [root@localhost ~]#tar zxf php-5.6.27.tar.gz 
  2. [root@localhost ~]# cd php-5.6.27/ 
  3. [root@localhost php-5.6.27]# ./configure --prefix=/usr/local/php5.6 --with-mysql=mysqlnd --with-pdo-mysql=mysqlnd --with-mysqli=mysqlnd --with-openssl --enable-fpm --enable-sockets --enable-sysvshm --enable-mbstring --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --with-mhash --with-mcrypt=/usr/local/limcrypt --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2--enable-maintainer-zts && make && make install 

 (3)提供php配置文件

  1. [root@localhost php-5.6.27]#cp php.ini-production /etc /php.ini 

(4)为php-fpm提供脚本

  1. [root@localhost php-5.6.27]#cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm 
  2. [root@localhost php-5.6.27]#chmod +x /etc/init.d/php-fpm 
  3. [root@localhost php-5.6.27]#chkconfig --add php-fpm 
  4. [root@localhost php-5.6.27]#chkconfig php-fpm on  

(5)提供php-fpm配置文件并编辑:

  1. [root@localhost php-5.6.27]#cp /usr/local/php5.6/etc/php-fpm.conf.default /usr/local/php5.6/etc/php-fpm.conf 
  2. [root@localhost php-5.6.27]#vi /usr/local/php5.6/etc/php-fpm.conf  

修改内容如下:

  1. pid = run/php-fpm.pid 
  2. listen = 0.0.0.0:9000 
  3. pm.max_children =300 
  4. pm.start_servers =20 
  5. pm.min_spare_servers = 20 
  6. pm.max_spare_servers= 100  

启动php-fpm服务:

  1. [root@localhost php-5.6.27]#service  php-fpm start 
  2. Starting php-fpm  done 
  3. [root@localhost php-5.6.27]# netstat -anpt | grep php-fpm 
  4.   
  5. tcp        0      0 0.0.0.0:9000            0.0.0.0:*               LISTEN      33807/php-fpm: mast 
  6. [root@localhost php-5.6.27]#firewall-cmd --permanent --add-port=9000/tcp 
  7. success 
  8. [root@localhost php-5.6.27]#firewall-cmd --reloadl 
  9. success  

在nginx.conf文件的server中添加下面内容支持php

  1. location ~ .*\.(php|php5)?$ { 
  2.             root html; 
  3.             fastcgi_pass 127.0.0.1:9000; 
  4.             fastcgi_index index.php; 
  5.             include fastcgi.conf; 
  6.             fastcgi_cache cache_fastcgi; 
  7.             fastcgi_cache_valid 200 302 1h; 
  8.             fastcgi_cache_valid 301 1d; 
  9.             fastcgi_cache_valid any 1m; 
  10.             fastcgi_cache_min_uses 1; 
  11.             fastcgi_cache_use_stale errortimeout invalid_header http_500; 
  12.             fastcgi_cache_keyhttp://$host$request_uri; 
  13.  

下面是nginx.conf的一个完整配置文件

  1. user www www; 
  2. worker_processes  4; 
  3. worker_cpu_affinity 0001 0010 0100 1000; 
  4. error_log  logs/error.log; 
  5. #error_log  logs/error.log  notice; 
  6. #error_log  logs/error.log  info; 
  7.    
  8. pid        logs/nginx.pid; 
  9.    
  10.    
  11. events { 
  12. use epoll; 
  13.    worker_connections  65535; 
  14.    multi_accept on
  15.    
  16.    
  17. http { 
  18. include       mime.types; 
  19.    default_type application/octet-stream; 
  20.    
  21.    #log_format  main  '$remote_addr - $remote_user [$time_local]"$request" ' 
  22.    #                  '$status$body_bytes_sent "$http_referer" ' 
  23.    #                 '"$http_user_agent" "$http_x_forwarded_for"'
  24.    
  25.    #access_log  logs/access.log  main; 
  26.    
  27.    sendfile        on
  28.    tcp_nopush     on
  29.    keepalive_timeout  65; 
  30.    tcp_nodelay on
  31.    client_header_buffer_size 4k; 
  32.    open_file_cache max=102400 inactive=20s; 
  33.    open_file_cache_valid 30s; 
  34.    open_file_cache_min_uses 1; 
  35.    client_header_timeout 15; 
  36.    client_body_timeout 15; 
  37.    reset_timedout_connection on
  38.    send_timeout 15; 
  39.    server_tokens off
  40.    client_max_body_size 10m; 
  41.    
  42.    fastcgi_connect_timeout     600; 
  43.    fastcgi_send_timeout 600; 
  44.    fastcgi_read_timeout 600; 
  45.    fastcgi_buffer_size 64k; 
  46.    fastcgi_buffers     4 64k; 
  47.    fastcgi_busy_buffers_size 128k; 
  48.    fastcgi_temp_file_write_size 128k; 
  49.     fastcgi_temp_path/usr/local/nginx1.10/nginx_tmp; 
  50.    fastcgi_intercept_errors on
  51.    fastcgi_cache_path /usr/local/nginx1.10/fastcgi_cache levels=1:2keys_zone=cache_fastcgi:128m inactive=1d max_size=10g; 
  52.    
  53. gzip on
  54.    gzip_min_length  2k; 
  55.    gzip_buffers     4 32k; 
  56.    gzip_http_version 1.1; 
  57.    gzip_comp_level 6; 
  58.    gzip_types  text/plain text/csstext/javascript application/json application/javascriptapplication/x-javascript application/xml; 
  59.    gzip_vary on
  60.    gzip_proxied any
  61. server { 
  62.        listen       80; 
  63.        server_name  www.benet.com; 
  64.    
  65.        #charset koi8-r; 
  66.    
  67.        #access_log logs/host.access.log  main; 
  68.    
  69.        location ~* ^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ { 
  70.             valid_referers none blocked  www.benet.com benet.com; 
  71.             if ($invalid_referer) { 
  72.                 #return 302  http://www.benet.com/img/nolink.jpg; 
  73.                 return 404; 
  74.                 break; 
  75.              } 
  76.              access_log off
  77.        } 
  78.        location / { 
  79.             root   html; 
  80.              index  index.php index.html index.htm; 
  81.        } 
  82.        location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)$ { 
  83.             expires 30d; 
  84.             #log_not_found off
  85.             access_log off
  86.        } 
  87.    
  88.        location ~* \.(js|css)$ { 
  89.             expires 7d; 
  90.             log_not_found off
  91.             access_log off
  92.        }       
  93.    
  94.        location = /(favicon.ico|roboots.txt) { 
  95.             access_log off
  96.             log_not_found off
  97.        } 
  98.        location /status { 
  99.             stub_status on
  100.        } 
  101.        location ~ .*\.(php|php5)?$ { 
  102.             root html; 
  103.             fastcgi_pass 127.0.0.1:9000; 
  104.             fastcgi_index index.php; 
  105.             include fastcgi.conf; 
  106.             fastcgi_cache cache_fastcgi; 
  107.            fastcgi_cache_valid 200 3021h; 
  108.             fastcgi_cache_valid 301 1d; 
  109.             fastcgi_cache_valid any 1m; 
  110.             fastcgi_cache_min_uses 1; 
  111.             fastcgi_cache_use_stale errortimeout invalid_header http_500; 
  112.             fastcgi_cache_keyhttp://$host$request_uri; 
  113.        } 
  114.        #error_page  404              /404.html; 
  115.    
  116.        # redirect server error pages to the static page /50x.html 
  117.        # 
  118.        error_page   500 502 503 504  /50x.html; 
  119.        location = /50x.html { 
  120.             root   html; 
  121.        } 
  122.   } 
  123.  

重载nginx服务

  1. [root@localhost ~]# /usr/local/nginx1.10/sbin/nginx -s reload 

三、验证、压力测试

(1)验证防盗链

使用apache做为一个测试站点,域名为www.test.com,在测试页上做一个超链接,链接nginx站点的一张图片

  1. [root@centos1 ~]# cat/var/www/html/index.html  
  2. <a href="http://www.benet.com/11.gif">lianjie</a>  

Nginx站点的网页目录结如下

  1. [root@localhost ~]# tree /usr/local/nginx1.10/html/ 
  2.   
  3. /usr/local/nginx1.10/html/ 
  4.   
  5. ├── 11.gif 
  6.   
  7. ├── 50x.html 
  8.   
  9. ├── img 
  10.   
  11. │   └── nolink.jpg 
  12.   
  13. ├── index.html 
  14.   
  15. ├── test.php  

在客户端浏览器中输入www.test.com (注意域名解析和防火墙)

 

 

 

在客户端浏览器中输入www.test.com 

点击页面链接 

 

 

点击页面链接 

从上图可以看到防盗链设置生效了

(2)验证gzip功能

使用谷歌浏览器测试访问,如下图显示结果:(提示:在访问测试页之前按F12键) 

 

 

使用谷歌浏览器测试访问 

用户访问test.php文件,在上图中content-encoding:gzip表明响应给用户的数据是压缩传输。

(3)压力测试

安装httpd-tools软件包

  1. [root@localhost ~]# yum -y install httpd-tools 
  2.  [root@localhost ~]# ab -c 500 -n 50000 http://192.168.129.150/index.html 
  3. This is ApacheBench, Version 2.3 <$Revision: 1430300 $> 
  4. Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ 
  5. Licensed to The Apache Software Foundation, http://www.apache.org/ 
  6. Benchmarking 192.168.129.150 (be patient) 
  7. Completed 5000 requests 
  8. Completed 10000 requests 
  9. Completed 15000 requests 
  10. Completed 20000 requests 
  11. Completed 25000 requests 
  12. Completed 30000 requests 
  13. Completed 35000 requests 
  14. Completed 40000 requests 
  15. Completed 45000 requests 
  16. Completed 50000 requests 
  17. Finished 50000 requests 
  18.   
  19. Server Software:        IIS 
  20. Server Hostname:        192.168.129.150 
  21. Server Port:            80 
  22. Document Path:          /index.html 
  23. Document Length:        612 bytes 
  24. Concurrency Level:      500 
  25. Time taken for tests:   3.607 seconds 
  26. Complete requests:      50000 
  27. Failed requests:        0 
  28. Write errors:           0 
  29. Total transferred:      41800000 bytes 
  30. HTML transferred:       30600000 bytes 
  31. Requests per second:    13862.78 [#/sec] (mean) 
  32. Time per request:       36.068 [ms] (mean) 
  33. Time per request:       0.072 [ms] (mean, across all concurrent requests) 
  34. Transfer rate:          11317.66 [Kbytes/sec] received 
  35. Connection Times (ms) 
  36.               min  mean[+/-sd] median   max 
  37. Connect:        0   16  25.5     15    1013 
  38. Processing:     4   18   4.1     18      71 
  39. Waiting:        1   14   4.3     12      36 
  40. Total:         17   34  25.7     34    1032 
  41. Percentage of the requests served within a certain time (ms) 
  42.   50%     34 
  43.   66%     35 
  44.   75%     35 
  45.   80%     36 
  46.   90%     37 
  47.   95%     37 
  48.   98%     38 
  49.   99%     64 
  50.  100%   1032 (longest request)  

第二次压力测试,比较两次的差异

  1. [root@localhost ~]# ab -c 1000 -n 100000 http://192.168.129.150/index.html 
  2. This is ApacheBench, Version 2.3 <$Revision: 1430300 $> 
  3. Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ 
  4. Licensed to The Apache Software Foundation, http://www.apache.org/ 
  5. Benchmarking 192.168.129.150 (be patient) 
  6. Completed 10000 requests 
  7. Completed 20000 requests 
  8. Completed 30000 requests 
  9. Completed 40000 requests 
  10. Completed 50000 requests 
  11. Completed 60000 requests 
  12. Completed 70000 requests 
  13. Completed 80000 requests 
  14. Completed 90000 requests 
  15. Completed 100000 requests 
  16. Finished 100000 requests 
  17.   
  18. Server Software:        IIS 
  19. Server Hostname:        192.168.129.150 
  20. Server Port:            80 
  21. Document Path:          /index.html 
  22. Document Length:        612 bytes 
  23. Concurrency Level:      1000 
  24. Time taken for tests:   7.332 seconds 
  25. Complete requests:      100000 
  26. Failed requests:        0 
  27. Write errors:           0 
  28. Total transferred:      83600000 bytes 
  29. HTML transferred:       61200000 bytes 
  30. Requests per second:    13638.90 [#/sec] (mean) 
  31. Time per request:       73.320 [ms] (mean) 
  32. Time per request:       0.073 [ms] (mean, across all concurrent requests) 
  33. Transfer rate:          11134.88 [Kbytes/sec] received 
  34. Connection Times (ms) 
  35.               min  mean[+/-sd] median   max 
  36. Connect:        0   40 114.5     27    1046 
  37. Processing:     7   32   9.4     33     237 
  38. Waiting:        1   24   8.8     23     232 
  39. Total:         29   72 115.3     62    1075 
  40. Percentage of the requests served within a certain time (ms) 
  41.   50%     62 
  42.   66%     69 
  43.   75%     71 
  44.   80%     72 
  45.   90%     75 
  46.   95%     76 
  47.   98%     80 
  48.   99%   1056 
  49.  100%   1075 (longest request)  

(5)xcache加速php

安装xcache

  1. wget    #下载 
  2. [root@localhost ~]#tar zxfxcache-3.2.0.tar.gz  #解压 
  3. [root@localhost ~]# cd xcache-3.2.0/           #进入安装目录 
  4. [root@localhost xcache-3.2.0]# /usr/local/php5.6/bin/phpize#用phpize生成configure配置文件 
  5. [root@localhost xcache-3.2.0]# ./configure --enable-xcache --enable-xcache-coverager --enable-xcache-optimizer --with-php-config=/usr/local/php5.6/bin/php-config   #配置 
  6. [root@localhost xcache-3.2.0]# make && make install     #编译、安装 
  7. Installing sharedextensions:                 /usr/local/php5.6/lib/php/extensions/no-debug-non-zts-20131226/  

安装完成之后,出现下面的界面,记住以下路径,后面会用到

/usr/local/php5.6/lib/php/extensions/no-debug-non-zts-20131226/

2)创建xcache缓存文件

  1. # touch /tmp/xcache 
  2. # chmod 777 /tmp/xcache  

3)拷贝xcache后台管理程序到网站根目录

  1. [root@localhost xcache-3.2.0]# cp -r htdocs/ /usr/local/nginx1.10/html/xcache 

4)配置php支持xcache

vi / etc/php.ini #编辑配置文件,在最后一行添加以下内容

  1. [xcache-common] 
  2. extension =/usr/local/php5.6/lib/php/extensions/no-debug-non-zts-20131226/xcache.so 
  3. [xcache.admin] 
  4. xcache.admin.enable_auth = Off 
  5. [xcache] 
  6. xcache.shm_scheme ="mmap" 
  7. xcache.size=60M 
  8. xcache.count =1 
  9. xcache.slots =8K 
  10. xcache.ttl=0 
  11. xcache.gc_interval =0 
  12. xcache.var_size=64M 
  13. xcache.var_count =1 
  14. xcache.var_slots =8K 
  15. xcache.var_ttl=0 
  16. xcache.var_maxttl=0 
  17. xcache.var_gc_interval =300 
  18. xcache.test =Off 
  19. xcache.readonly_protection = Off 
  20. xcache.mmap_path="/tmp/xcache" 
  21. xcache.coredump_directory ="" 
  22. xcache.cacher =On 
  23. xcache.stat=On 
  24. xcache.optimizer =Off 
  25. [xcache.coverager] 
  26. xcache.coverager =On 
  27. xcache.coveragedump_directory=""  

测试

service php-fpm restart #重启php-fpm

浏览器打开网站根目录下面的xcache

http://www.benet.com/xcache可以看到如下页面: 

 

 

 

测试对php动态页面的压力测试

  1. [root@localhost xcache-3.2.0]# ab -c 1000 -n 100000 http://192.168.129.150/test.php 
  2. This is ApacheBench, Version 2.3 <$Revision: 1430300 $> 
  3. Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ 
  4. Licensed to The Apache Software Foundation, http://www.apache.org/ 
  5.   
  6. Benchmarking 192.168.129.150 (be patient) 
  7. Completed 10000 requests 
  8. Completed 20000 requests 
  9. Completed 30000 requests 
  10. Completed 40000 requests 
  11. Completed 50000 requests 
  12. Completed 60000 requests 
  13. Completed 70000 requests 
  14. Completed 80000 requests 
  15. Completed 90000 requests 
  16. Completed 100000 requests 
  17. Finished 100000 requests 
  18.   
  19.   
  20. Server Software:        IIS 
  21. Server Hostname:        192.168.129.150 
  22. Server Port:            80 
  23.   
  24. Document Path:          /test.php 
  25. Document Length:        16 bytes 
  26.   
  27. Concurrency Level:      1000 
  28. Time taken for tests:   7.031 seconds 
  29. Complete requests:      100000 
  30. Failed requests:        0 
  31. Write errors:           0 
  32. Non-2xx responses:      100000 
  33. Total transferred:      20000000 bytes 
  34. HTML transferred:       1600000 bytes 
  35. Requests per second:    14223.52 [#/sec] (mean) 
  36. Time per request:       70.306 [ms] (mean) 
  37. Time per request:       0.070 [ms] (mean, across all concurrent requests) 
  38. Transfer rate:          2778.03 [Kbytes/sec] received 
  39.   
  40. Connection Times (ms) 
  41.               min  mean[+/-sd] median   max 
  42. Connect:        0   39 133.7     20    1035 
  43. Processing:     4   27  12.4     26     238 
  44. Waiting:        0   20   9.6     18     227 
  45. Total:         17   65 135.7     50    1254 
  46.   
  47. Percentage of the requests served within a certain time (ms) 
  48.   50%     50 
  49.   66%     54 
  50.   75%     57 
  51.   80%     59 
  52.   90%     62 
  53.   95%     65 
  54.   98%    213 
  55.   99%   1047 
  56.  100%   1254 (longest request)  

主要参数说明:

Requests per second:平均每秒处理事务数

Time per request:平均事务响应时间

Tranfer rate:平均每秒网络吞吐量

责任编辑:庞桂玉 来源: 51CTO博客
相关推荐

2019-08-25 07:15:47

Nginx防盗链Linux

2011-05-31 14:57:17

PHP盗链

2020-06-15 09:41:47

网络安全数据技术

2024-01-31 23:27:50

盗链Node.js

2020-09-01 16:56:58

华为云

2014-04-04 10:16:51

Nginx配置Nginx性能优化

2014-08-08 13:30:44

Nginx

2013-01-30 10:12:24

NginxNginx优化高并发

2020-12-11 18:58:21

Nginx浏览器缓存

2010-03-29 16:48:18

Nginx内核优化

2010-03-29 16:31:48

2010-03-29 10:12:04

Nginx优化设置

2013-11-21 11:03:29

Nginx性能优化

2010-03-29 14:55:18

Nginx日志

2010-03-29 09:23:00

2011-05-23 09:32:43

2011-11-08 13:46:44

静态文件Nginx优化

2017-07-25 12:07:14

MySQL索引SQL

2018-09-11 09:41:19

2022-01-05 14:02:31

前端Nginx单页加载
点赞
收藏

51CTO技术栈公众号