关于nginx网站优化方面的总结

一、编译安装前的优化

1.NGINX简介
NGINX以事件驱动(epoll)的方式编写,有着非常好的性能,同时也是一个非常高效的反向代理、负载平衡。但是NGINX并不支持CGI方式运行,原因是可以减少带来的一些程序上的漏洞。所以必须使用FastCGI方式来执行PHP程序。
由于NGINX本身的一些优点,轻量,开源,易用,越来越多的公司使用nginx作为web应用服务器。
2.NGINX优化
(1)编译前的优化主要是用来修改程序名等,目的是更改源码隐藏软件名称和版本号。

[root@www ~]# yum -y install gcc gcc-c++ make libtool zlib zlib-devel pcre pcre-devel openssl openssl-devel
[root@www ~]# tar zxf nginx-1.10.2.tar.gz
[root@www ~]# cd nginx-1.10.2/
#隐藏软件名称和版本号
[root@www nginx-1.10.2]# vim src/core/nginx.h
#此行修改的是你想要的版本
#define NGINX_VERSION "1.10.2"
#此行修改的是你想修改的软件名称
#define NGINX_VER "nginx/" NGINX_VERSION
修改上面的信息可更改nginx显示版本。
例如:(curl –I可看到,请求头和响应头显示)

#define NGINX_VERSION "7.0"
#define NGINX_VER "IIS/" NGINX_VERSION
#修改HTTP头信息中的connection字段,防止回显具体版本号。

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

[root@www nginx-1.10.2]# vim src/http/ngx_http_header_filter_module.c
修改前:
static char ngx_http_server_string[] = "Server: nginx" CRLF;
修改后:
static char ngx_http_server_string[] = "Server: IIS" CRLF;

(3)定义了http错误码的返回
有时页面程序出现错误,Nginx会返回相应的错误代码,回显时会带上nginx和版本号,需要把他隐藏起来。

[root@www nginx-1.10.2]# vi src/http/ngx_http_special_response.c
修改前
static u_char ngx_http_error_tail[] =
"<hr><center>nginx</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;
修改后
static u_char ngx_http_error_tail[] =
"<hr><center>IIS</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;

二、编译安装NGINX

1.安装NGINX

[root@www ~]# groupadd www  #添加www组
[root@www ~]# useradd -g www www -s /sbin/nologin  #创建nginx运行账户www并加入到www组,不允许www用户直接登录系统
[root@www 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
[root@www nginx-1.10.2]# 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是通过编译安装。

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

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

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

3.启动nginx

[root@www nginx-1.10.2]# nginx 
[root@www nginx-1.10.2]# netstat -anpt | grep nginx
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 9834/nginx: master

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

[root@www ~]# curl -I http://127.0.0.1
HTTP/1.1 200 OK
Server: IIS/7.0
Date: Sat, 05 Nov 2016 14:38:21 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Sat, 05 Nov 2016 14:19:47 GMT
Connection: keep-alive
ETag: "581dea83-264"
Accept-Ranges: bytes
[root@www ~]# nginx -h
nginx version: IIS/7.0
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]
Options:
-v : show version and exit
-V : show version and configure options then exit
-t : test configuration and exit
-T : test configuration, dump it and exit
-q : suppress non-error messages during configuration testing
-s signal : send signal to a master process: stop, quit, reopen, reload
-p prefix : set prefix path (default: /usr/local/nginx1.10/)
-c filename : set configuration file (default: conf/nginx.conf)
-g directives : set global directives out of configuration file

三、NGINX配置项优化

1.查看NGINX进程

[root@www ~]# ps -ef | grep nginx
root 9834 1 0 22:36 ? 00:00:00 nginx: master process nginx
www 9953 9834 0 22:43 ? 00:00:00 nginx: worker process

可以看到在查看时,worker进程是nginx程序用户,但是master进程还是root,其中,master是监控进程,也叫主进程,worker是工作进程,部分还有cache相关进程。
在这里插入图片描述
可以理解为master是管理员,worker进程才是为用户提供服务的。
2.Nginx运行工作进程数
一般设置成CPU的核心数或者核心数x2。
如果不了解cpu的核数,可以top命令之后按1查看,也可以查看/proc/cpuinfo文件

# grep ^processor /proc/cpuinfo | wc -l

查看NGINX配置文件

[root@www ~]# vim /usr/local/nginx1.10/conf/nginx.conf
worker_processes 4;
[root@www ~]# /usr/local/nginx1.10/sbin/nginx -s reload
[root@www ~]# ps -aux | grep nginx | grep -v grep
root 9834 0.0 0.0 47556 1948 ? Ss 22:36 0:00 nginx: master process nginx
www 10135 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process
www 10136 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process
www 10137 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process
www 10138 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process

3.Nginx运行CPU亲和力
(1)比如4核配置

worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;

(2)比如8核配置

worker_processes 8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

worker_processes最多开启8个,8个以上性能提升不会再提升,而且稳定性变得更低,所以8个进程够用了。
4.Nginx最多可以打开文件数

worker_rlimit_nofile 65535;

指当一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(ulimit -n)与nginx进程数相除,但是nginx分配请求并不是那么均匀,所以最好与ulimit -n的值保持一致。
注意
文件资源限制的配置可以在/etc/security/limits.conf设置,针对root/user等各个用户或者*代表所有用户来设置。

*  soft  nofile  65535
*  hard  nofile  65535

用户重新登录生效(ulimit -n)。
5.Nginx事件处理模型

events {
use epoll;
worker_connections 65535;
multi_accept on;
}

参数说明

use epoll;
#nginx采用epoll事件模型,处理效率高。

work_connections 65535;
#单个worker进程允许客户端最大连接数,这个数值一般根据服务器性能和内存来制定,实际最大值就是worker进程数乘以work_connections。实际上65535就足够了,这些都算并发值,一个网站的并发达到这么大的数量,也算一个大站了。

multi_accept on;
#告诉nginx收到一个新连接,通知后接受尽可能多的连接。

6.开启高效传输模式

http {
include mime.types;
default_type application/octet-stream;
……
sendfile on;
tcp_nopush on;
……

参数说明

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

default_type application/octet-stream;
#默认媒体类型足够。

sendfile on;
#开启高效文件传输模式,指定nginx是否调用sendfile函数来输出文件,对于普通应用设为on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。
注意:如果图片显示不正常把这个改成off。

tcp_nopush on;
#必须在sendfile开启模式才有效,防止网路阻塞,积极的减少网络报文段的数量(告诉nginx在一个数据包里发送所有头文件,而不一个接一个的发送。)

7.连接超时时间
主要目的是保护服务器资源,CPU,内存,控制连接数,因为建立连接也会消耗资源。

keepalive_timeout 60;
tcp_nodelay on;
client_header_buffer_size 4k;
open_file_cache max=102400 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 1;
client_header_timeout 15;
client_body_timeout 15;
reset_timedout_connection on;
send_timeout 15;
server_tokens off;
client_max_body_size 10m;

参数说明

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

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

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

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

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

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

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

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

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

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

server_tokens off;
#并不会让nginx执行的速度更快,但它可以关闭在错误页面中的nginx版本数字,这样对于安全性是有好处的。

client_max_body_size 10m;
#上传文件大小限制。

8.fastcgi调优

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

Cache:写入缓存区
Buffer:读取缓存区
Fastcgi是静态服务和动态服务的一个接口。
参数说明

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的两倍,该数值设置小时,若负载上来时可能报502 Bad Gateway。

fastcgi_temp_path /usr/local/nginx1.10/nginx_tmp;
#缓存临时目录

fastcgi_intercept_errors on;
#这个指令指定是否传递4xx和5xx错误信息到客户端,或者允许nginx使用error_page处理错误信息。
注:静态文件不存在会返回404页面,但是php页面则返回空白页。

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

其他调优介绍

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_key http://$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)的压力。

9.gzip调优
使用gzip压缩功能,可以节约带宽,加快传输速度,节约成本,使客户有更好的体验。
Nginx启用压缩功能需要ngx_http_gzip_module模块,apache使用的是mod_deflate。
一般需要压缩的内容有:文本,js,html,css,对于图片,视频,flash不压缩,同时也要注意,使用gzip的功能是会消耗CPU的。

gzip on;
gzip_min_length 2k;
gzip_buffers 4 32k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
gzip_vary on;
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/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
#用来指定压缩的类型,‘text/html’类型总是会被压缩。
#默认值:gzip_types text/html(默认不对js/css文件进行压缩)
#压缩类型,匹配MIME类型进行压缩
#不能用通配符text/*
#(无论是否指定)text/html默认已经压缩
#设置哪压缩种文本文件可参考conf/mime.types

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

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

location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)$ {
    expires 30d;
    #log_not_found off;
    access_log off;
}

location ~* \.(js|css)$ {
    expires 7d;
    log_not_found off;
    access_log off;
}

参数说明

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

总结
expire功能优点

(1)expires可以降低网站购买的带宽,节约成本;

(2)同时提升用户访问体验;

(3)减轻服务的压力,节约服务器成本,是web服务非常重要的功能。

expire功能缺点

被缓存的页面或数据更新了,用户看到的可能还是旧的内容,反而影响用户体验。
解决办法:
第一个缩短缓存时间,例如:1天,但不彻底,除非更新频率大于1天。
第二个对缓存的对象改名。

网站不希望被缓存的内容

(1)网站流量统计工具;

(2)更新频繁的文件(google的logo);

11.防盗链
防止别人直接从你的网站引用图片等链接,消耗你的资源和网络流量。
解决办法

(1)水印,品牌宣传,你的带宽,服务器足够;

(2)防火墙,直接控制,前提是你知道IP来源;

(3)防盗链策略;

下面的方法是直接给予404的错误提示。

location ~* ^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
    valid_referers none blocked www.benet.com benet.com;
    if ($invalid_referer) {
        #return 302 http://www.benet.com/img/nolink.jpg;
        return 404;
        break;
    }
    access_log off;
}
四、Linux系统参数优化

1.内核参数优化项说明

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-WAIT sockets重新用于新的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 = 10240 87380 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攻击。

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

[root@localhost ~]# vim /etc/sysctl.conf
fs.file-max = 999999
net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 10240 87380 12582912
net.ipv4.tcp_wmem = 10240 87380 12582912
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 40960
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_keepalive_time = 30
net.ipv4.ip_local_port_range = 1024 65000

执行sysctl -p使内核修改生效。
2.关于系统连接数的优化
linux默认值open files为1024。

# ulimit -n
1024

说明server只允许同时打开1024个文件。
使用ulimit -a可以查看当前系统的所有限制值,使用ulimit -n可以查看当前的最大打开文件数。
新装的linux默认只有1024,当做负载较大的服务器时,很容易遇到error: too many open files。
因此,需要将其改大,在/etc/security/limits.conf最后增加。

*  soft  nofile  65535
*  hard  nofile  65535
*  soft  noproc  65535
*  hard  noproc  65535
五、部署lnmp

1.安装php
(1)解决依赖关系

[root@www ~]# yum -y install libxml2-devel libcurl-devel openssl-devel bzip2-devel

安装libmcrypt

[root@www ~]# tar zxf libmcrypt-2.5.7.tar.gz
[root@wwwr ~]# cd libmcrypt-2.5.7/
[root@www libmcrypt-2.5.7]# ./configure --prefix=/usr/local/libmcrypt && make && make install

(2)编译安装php

[root@www ~]# tar zxf php-5.6.27.tar.gz
[root@www ~]# cd php-5.6.27/
[root@www 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/libmcrypt --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2 --enable-maintainer-zts
[root@www php-5.6.27]# make && make install

(3)提供php配置文件

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

(4)为php-fpm提供脚本

[root@www php-5.6.27]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@www php-5.6.27]# chmod +x /etc/init.d/php-fpm
[root@www php-5.6.27]# chkconfig --add php-fpm
[root@www php-5.6.27]# chkconfig php-fpm on

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

# cp /usr/local/php5.6/etc/php-fpm.conf.default /usr/local/php5.6/etc/php-fpm.conf
[root@www ~]# vim /usr/local/php5.6/etc/php-fpm.conf
修改内容如下:
pid = run/php-fpm.pid
listen = 0.0.0.0:9000
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35

启动php-fpm服务

[root@www ~]# service php-fpm start
Starting php-fpm done
[root@www ~]# netstat -anpt | grep php-fpm
tcp 0 0 0.0.0.0:9000 0.0.0.0:* LISTEN 25456/php-fpm: mast 

如果防火墙没关,进行下面的设置

[root@www ~]# firewall-cmd --permanent --add-port=9000/tcp
success
[root@www ~]# firewall-cmd --reload
Success

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

location ~ .*\.(php|php5)?$ {
                root html;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi.conf;
                fastcgi_cache cache_fastcgi;
                fastcgi_cache_valid 200 302 1h;
                fastcgi_cache_valid 301 1d;
                fastcgi_cache_valid any 1m;
                fastcgi_cache_min_uses 1;
                fastcgi_cache_use_stale error timeout invalid_header http_500;
                fastcgi_cache_key http://$host$request_uri;
}

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

user www www;
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

pid logs/nginx.pid;

events {
    use epoll;
    worker_connections 65535;
    multi_accept on;
}

http {
    include mime.types;
    default_type application/octet-stream;
    
    #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    # '$status $body_bytes_sent "$http_referer" '
    # '"$http_user_agent" "$http_x_forwarded_for"';
    
    #access_log logs/access.log main;
    
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 65;
    tcp_nodelay on;
    client_header_buffer_size 4k;
    open_file_cache max=102400 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 1;
    client_header_timeout 15;
    client_body_timeout 15;
    reset_timedout_connection on;
    send_timeout 15;
    server_tokens off;
    client_max_body_size 10m;

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

    gzip on;
    gzip_min_length 2k;
    gzip_buffers 4 32k;
    gzip_http_version 1.1;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
    gzip_vary on;
    gzip_proxied any;
    server {
        listen 80;
        server_name www.benet.com;
        
        #charset koi8-r;
        
        #access_log logs/host.access.log main;
        
        location ~* ^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
            valid_referers none blocked www.benet.com benet.com;
            if ($invalid_referer) {
                #return 302 http://www.benet.com/img/nolink.jpg;
                return 404;
                break;
            }
            access_log off;
        }
        location / {
            root html;
            index index.php index.html index.htm;
        }
        location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)$ {
            expires 30d;
            #log_not_found off;
            access_log off;
        }
        
        location ~* \.(js|css)$ {
            expires 7d;
            log_not_found off;
            access_log off;
        } 

        location = /(favicon.ico|roboots.txt) {
            access_log off;
            log_not_found off;
        }
        location /status {
            stub_status on;
        }
        location ~ .*\.(php|php5)?$ {
            root html;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi.conf;
            fastcgi_cache cache_fastcgi;
            fastcgi_cache_valid 200 302 1h;
            fastcgi_cache_valid 301 1d;
            fastcgi_cache_valid any 1m;
            fastcgi_cache_min_uses 1;
            fastcgi_cache_use_stale error timeout invalid_header http_500;
            fastcgi_cache_key http://$host$request_uri;
        }
        #error_page 404 /404.html;

        #redirect server error pages to the static page /50x.html
        #error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root html;
        }
    }
}

重载nginx服务

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

2.验证、压力测试
(1)验证防盗链
使用apache做为一个测试站点,域名为www.test.com,在测试页上做一个超链接,链接nginx站点的一张图片。

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

Nginx站点的网页目录结如下

tree /usr/local/nginx1.10/html/
/usr/local/nginx1.10/html/
├── 11.gif
├── 50x.html
├── img
│ └── nolink.jpg
├── index.html
├── test.php

在客户端浏览器中输入www.test.com
在这里插入图片描述
点击页面链接
在这里插入图片描述
可以看到防盗链设置生效了。
(2)验证gzip功能
使用谷歌浏览器测试访问(提示:在访问测试页之前按F12键)。
在这里插入图片描述
用户访问test.php文件,在上图中content-encoding:gzip表明响应给用户的数据是压缩传输。
(3)压力测试
安装httpd-tools软件包

[root@www ~]# yum -y install httpd-tools
[root@www ~]# ab -c 500 -n 50000 http://www.benet.com/index.html
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking www.benet.com (be patient)
Completed 5000 requests
Completed 10000 requests
Completed 15000 requests
Completed 20000 requests
Completed 25000 requests
Completed 30000 requests
Completed 35000 requests
Completed 40000 requests
Completed 45000 requests
Completed 50000 requests
Finished 50000 requests

Server Software: IIS
Server Hostname: www.benet.com
Server Port: 80

Document Path: /index.html
Document Length: 612 bytes

Concurrency Level: 500
Time taken for tests: 5.734 seconds
Complete requests: 50000
Failed requests: 0
Write errors: 0
Total transferred: 41800000 bytes
HTML transferred: 30600000 bytes
Requests per second: 8719.82 [#/sec] (mean)
Time per request: 57.341 [ms] (mean)
Time per request: 0.115 [ms] (mean, across all concurrent requests)
Transfer rate: 7118.92 [Kbytes/sec] received

Connection Times (ms)
min mean[+/-sd] median max
Connect: 1 25 4.2 25 38
Processing: 7 32 5.5 31 47
Waiting: 4 24 6.8 21 39
Total: 40 57 3.9 57 71

Percentage of the requests served within a certain time (ms)
50% 57
66% 59
75% 59
80% 60
90% 61
95% 62
98% 63
99% 64
100% 71 (longest request)

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

[root@www ~]# ab -c 1000 -n 100000 http://www.benet.com/index.html
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking www.benet.com (be patient)
Completed 10000 requests
Completed 20000 requests
Completed 30000 requests
Completed 40000 requests
Completed 50000 requests
Completed 60000 requests
Completed 70000 requests
Completed 80000 requests
Completed 90000 requests
Completed 100000 requests
Finished 100000 requests

Server Software: IIS
Server Hostname: www.benet.com
Server Port: 80

Document Path: /index.html
Document Length: 612 bytes

Concurrency Level: 1000
Time taken for tests: 12.010 seconds
Complete requests: 100000
Failed requests: 0
Write errors: 0
Total transferred: 83600000 bytes
HTML transferred: 61200000 bytes
Requests per second: 8326.49 [#/sec] (mean)
Time per request: 120.099 [ms] (mean)
Time per request: 0.120 [ms] (mean, across all concurrent requests)
Transfer rate: 6797.80 [Kbytes/sec] received

Connection Times (ms)
min mean[+/-sd] median max
Connect: 1 53 8.9 53 82
Processing: 17 67 11.4 66 98
Waiting: 0 49 14.3 43 84
Total: 70 119 6.5 120 140

Percentage of the requests served within a certain time (ms)
50% 120
66% 122
75% 123
80% 124
90% 126
95% 128
98% 129
99% 130
100% 140 (longest request)

(4)xcache加速php
安装xcache

wget http://xcache.lighttpd.net/pub/Releases/3.2.0/xcache-3.2.0.tar.gz  #下载
[root@www ~]# tar zxf xcache-3.2.0.tar.gz  #解压
[root@www ~]# cd xcache-3.2.0/  #进入安装目录
[root@www xcache-3.2.0]# /usr/local/php5.6/bin/phpize  #用phpize生成configure配置文件
[root@www xcache-3.2.0]# ./configure --enable-xcache --enable-xcache-coverager --enable-xcache-optimizer --with-php-config=/usr/local/php5.6/bin/php-config  #配置
[root@www xcache-3.2.0]# make && make install  #编译、安装
Installing shared extensions: 
/usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/

安装完成之后,出现下面的界面,记住以下路径,后面会用到
/usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/
创建xcache缓存文件

# touch /tmp/xcache
# chmod 777 /tmp/xcache

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

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

配置php支持xcache

vim / etc/php.ini  #编辑配置文件,在最后一行添加以下内容。
[xcache-common]
extension = /usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/xcache.so
[xcache.admin]
xcache.admin.enable_auth = Off
[xcache]
xcache.shm_scheme ="mmap"
xcache.size=60M
xcache.count =1
xcache.slots =8K
xcache.ttl=0
xcache.gc_interval =0
xcache.var_size=64M
xcache.var_count =1
xcache.var_slots =8K
xcache.var_ttl=0
xcache.var_maxttl=0
xcache.var_gc_interval =300
xcache.test =Off
xcache.readonly_protection = Off
xcache.mmap_path ="/tmp/xcache"
xcache.coredump_directory =""
xcache.cacher =On
xcache.stat=On
xcache.optimizer =Off
[xcache.coverager]
xcache.coverager =On
xcache.coveragedump_directory =""

测试

service php-fpm restart  #重启php-fpm

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

http:// http://www.benet.com/xcache

可以看到如下页面:
在这里插入图片描述
测试对 php 动态页面的压力测试

[root@www ~]# ab -c 1000 -n 100000 http://www.benet.com/test.php
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking www.benet.com (be patient)
Completed 10000 requests
Completed 20000 requests
Completed 30000 requests
Completed 40000 requests
Completed 50000 requests
Completed 60000 requests
Completed 70000 requests
Completed 80000 requests
Completed 90000 requests
Completed 100000 requests
Finished 100000 requests

Server Software: IIS
Server Hostname: www.benet.com
Server Port: 80

Document Path: /test.php
Document Length: 85102 bytes

Concurrency Level: 1000
Time taken for tests: 13.686 seconds
Complete requests: 100000
Failed requests: 0
Write errors: 0
Total transferred: 8527900000 bytes
HTML transferred: 8510200000 bytes
Requests per second: 7306.71 [#/sec] (mean)
Time per request: 136.861 [ms] (mean)
Time per request: 0.137 [ms] (mean, across all concurrent requests)
Transfer rate: 608504.46 [Kbytes/sec] received

Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 17 5.5 17 81
Processing: 21 119 10.8 121 140
Waiting: 1 17 6.7 16 68
Total: 50 136 8.1 137 151

Percentage of the requests served within a certain time (ms)
50% 137
66% 139
75% 140
80% 141
90% 143
95% 144
98% 146
99% 148
100% 151 (longest request)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值