Nginx优化与防盗链+单机部署LNMP

Nginx优化与防盗链+单机部署LNMP

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、编译安装前的优化

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

(1)安装 zlib-devel、pcre-devel 等依赖包
[root@nginx ~]# yum -y install gcc gcc-c++ make libtool zlib zlib-devel pcre pcre-devel openssl openssl-devel
(2)下载Nginx源码包
[root@nginx ~]# wget http://nginx.org/download/nginx-1.10.2.tar.gz
(3)解压源码包
[root@nginx ~]# tar zxf nginx-1.10.2.tar.gz 
[root@nginx ~]# cd nginx-1.10.2/
(4)隐藏软件名称和版本号
[root@nginx nginx-1.10.2]# vim src/core/nginx.h
# 此行修改的是你想要的版本
#define NGINX_VERSION      "1.10.2"  # 第13行
# 此行修改的是你想修改的软件名称
#define NGINX_VER          "nginx/" NGINX_VERSION  # 第14行

修改上面的信息,即可更改 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。对通用头的扩展要求通讯双方都支持此扩展,如果存在不支持的通用头,一般将会作为实体头处理。那么也就是说有部分设备,或者是软件,能获取到 connection,部分不能,要隐藏就要彻底!

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

定义了 http 错误码的返回:

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

[root@nginx nginx-1.10.2]# vim src/http/ngx_http_special_response.c
# 修改前
static u_char ngx_http_error_tail[] =
"<hr><center>nginx</center>" CRLF # 第29行
"</body>" CRLF
"</html>" CRLF
;
# 修改后
static u_char ngx_http_error_tail[] =
"<hr><center>IIS</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;
2、安装nginx
(1)添加 nginx 组

创建nginx运行账户nginx并加入到nginx 组,不允许 www 用户直接登录系统

[root@nginx nginx-1.10.2]# groupadd nginx
[root@nginx nginx-1.10.2]# useradd -g nginx nginx -s /sbin/nologin
(2)编译安装
[root@nginx 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=nginx --group=nginx
[root@nginx 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 查看帮助

[root@nginx nginx-1.10.2]# ln -s /usr/local/nginx1.10/sbin/nginx /usr/local/sbin/
[root@nginx nginx-1.10.2]# nginx -t
nginx: the configuration file /usr/local/nginx1.10/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1.10/conf/nginx.conf test is successful
(3)启动 nginx
[root@nginx nginx-1.10.2]# nginx
[root@nginx nginx-1.10.2]# netstat -anpt | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      8303/nginx: master
(4)测试是否隐藏了版本和软件名
[root@nginx ~]# curl -I 127.0.0.1
HTTP/1.1 200 OK
Server: IIS/7.0
Date: Fri, 12 Jun 2020 01:08:48 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Fri, 12 Jun 2020 00:59:55 GMT
Connection: keep-alive
ETag: "5ee2d38b-264"
Accept-Ranges: bytes
3、nginx配置项优化
[root@nginx ~]# ps -ef | grep nginx
root       8303      1  0 09:07 ?        00:00:00 nginx: master process nginx
nginx      8304   8303  0 09:07 ?        00:00:00 nginx: worker process

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

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

(1)Nginx 运行 工作置 进程个数

一般我们设置 CPU 的核心或者核心数 x2

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

[root@nginx ~]# grep ^processor /proc/cpuinfo | wc -l
1
[root@nginx ~]# vim /usr/local/nginx1.10/conf/nginx.conf
worker_processes  2;
[root@nginx ~]# nginx -s reload
[root@nginx ~]# ps -aux | grep nginx | grep -v grep
root       8303  0.0  0.1  46028  1920 ?        Ss   09:07   0:00 nginx: master process nginx
nginx     10242  0.0  0.2  48540  2072 ?        S    09:14   0:00 nginx: worker process
nginx     10243  0.0  0.2  48540  2072 ?        S    09:14   0:00 nginx: worker process
(2)Nginx 运行 CPU 亲和力

比如 4 核配置

worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000

比如 8 核配置

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

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

(3)Nginx 最多可以打开文件数
worker_rlimit_nofile 65535;

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

注:

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

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

[root@nginx ~]# vim /etc/security/limits.conf
*               soft    nofile          65535
*               hard    nofile          65535
[root@nginx ~]# ulimit -n
65535
(4)Nginx 事件处理模型
events {
    use epoll;
    worker_connections  65535;
    multi_accept on;
}

nginx 采用 epoll 事件模型,处理效率高

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

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

(5)开启高效传输模式
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;

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

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

tcp_nopush on;

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

(6)连接超时时间

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

    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;

keepalived_timeout

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

tcp_nodelay;

也是防止网络阻塞,不过要包涵在 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;

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

上传文件大小限制

(7)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

缓存临时目录

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: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_key http://hosthostrequest_uri; #该指令用来设置web缓存的Key值,nginx根据Key值 md5 哈希存储.一般根据host()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)的压力

(8)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/css text/xml application/javascript;

用来指定压缩的类型,‘text/html’类型总是会被压缩

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

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

不能用通配符 text/*

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

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

gzip_vary on;

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

(9)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 功能优点:

  • expires 可以降低网站购买的带宽,节约成本
  • 同时提升用户访问体验
  • 减轻服务的压力,节约服务器成本,是 web 服务非常重要的功能

expire 功能缺点:

  • 被缓存的页面或数据更新了,用户看到的可能还是旧的内容,反而影响用户体验

解决办法:

  • 第一个缩短缓存时间,例如:1 天,但不彻底,除非更新频率大于 1 天;
  • 第二个对缓存的对象改名

网站不希望被缓存的内容:

  • 网站流量统计工具
  • 更新频繁的文件
(10)防盗链

防止别人直接从你网站引用图片等链接,消耗了你的资源和网络流量,那么我们的解决办法
由几种:

  • 水印,品牌宣传,你的带宽,服务器足够
  • 防火墙,直接控制,前提是你知道 IP 来源
  • 防盗链策略 下面的方法是直接给予 404 的错误提示
        location ~* ^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
            valid_referers none blocked 192.168.1.20;
            if ($invalid_referer) {
                #return 302 http://192.168.1.20/img/nolink.jpg;
                return 404;
                break;
            }
            access_log off;
        }
(11)内核参数优化
[root@nginx ~]# 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
[root@nginx ~]# sysctl -p

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 攻击

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

linux 默认值 open files 为 1024】

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

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

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

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

* soft nofile 65535
* hard nofile 65535
* soft noproc 65535
* hard noproc 65535

二、部署LNMP

软件连接

提取码:vzsu

1、安装php
(1)解决依赖关系
[root@nginx ~]# yum -y install libxml2-devel libcurl-devel openssl-devel bzip2-devel

安装libmcypt

[root@nginx libmcrypt-2.5.7]# ./configure --prefix=/usr/local/libmcrypt && make && make install
(2)编译安装php
[root@nginx ~]# tar zxf php-5.6.27.tar.gz 
[root@nginx ~]# cd php-5.6.27/
[root@nginx 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@nginx php-5.6.27]# make && make install
(3)提供php配置文件
[root@nginx php-5.6.27]# cp php.ini-production /etc/php.ini
(4)为 php-fpm 提供脚本
[root@nginx php-5.6.27]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@nginx php-5.6.27]# chmod +x /etc/init.d/php-fpm 
[root@nginx php-5.6.27]# chkconfig --add php-fpm
[root@nginx php-5.6.27]# chkconfig php-fpm on
(5)提供 php-fpm 配置文件并编辑
[root@nginx php-5.6.27]# cp /usr/local/php5.6/etc/php-fpm.conf.default /usr/local/php5.6/etc/php-fpm.conf
[root@nginx php-5.6.27]# 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@nginx php-5.6.27]# service php-fpm start
Starting php-fpm  done
[root@nginx php-5.6.27]# netstat -anpt | grep php-fpm
tcp        0      0 0.0.0.0:9000            0.0.0.0:*               LISTEN      125567/php-fpm: mas
[root@nginx ~]# firewall-cmd --permanent --add-port=9000/tcp
success
[root@nginx ~]# firewall-cmd --reload
Success

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

[root@nginx ~]# vim /usr/local/nginx1.10/conf/nginx.conf
        location / {
            root   html;
            index  index.php index.html index.htm;
        }
        
        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 服务

[root@nginx ~]# nginx -s reload

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

[root@nginx ~]# cat /usr/local/nginx1.10/conf/nginx.conf

user  nginx nginx;
worker_processes  2;
worker_cpu_affinity 01 10;
worker_rlimit_nofile 65535;

#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  0;
    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  localhost;

        #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 192.168.1.20;
	    if ($invalid_referer) {
		#return 302 http://192.168.1.20/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 ~ .*\.(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;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

三、验证、压力测试

1、验证防盗链

使用httpd做为一个测试站点,192.168.1.30,在测试页上做一个超链接,链接 nginx站点的一张图片

[root@httpd ~]# vim /var/www/html/index.html
<a href="http://192.168.1.20/11.gif">lianjie</a>

Nginx 站点的网页目录结如下

[root@nginx ~]# tree /usr/local/nginx1.10/html/
/usr/local/nginx1.10/html/
├── 11.gif
├── 50x.html
├── img
│   └── nolink.jpg
├── index.html
└── test.php

在客户端浏览器中输入192.168.1.30

点击页面链接

将return的404关闭,指定跳转文件

return 302 http://192.168.1.20/img/nolink.jpg;
                #return 404;

11.gif图片

nolink.jpg图片

根据防盗链的设置,会跳转到nolink.jpg图片
配置已经生效

2、验证gzip功能

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

3、压力测试

安装 httpd-tools 软件包

[root@nginx ~]# yum -y install httpd-tools
[root@nginx ~]# ab -c 500 -n 50000 http://192.168.1.20/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 192.168.1.20 (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:        192.168.1.20
Server Port:            80

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

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

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   10   3.9     10      20
Processing:     9   16   4.0     15      29
Waiting:        0    8   1.0      8      12
Total:         15   25   1.5     25      36

Percentage of the requests served within a certain time (ms)
  50%     25
  66%     26
  75%     26
  80%     26
  90%     27
  95%     28
  98%     29
  99%     30
 100%     36 (longest request)

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

[root@nginx ~]# ab -c 1000 -n 100000 http://192.168.1.20/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 192.168.1.20 (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:        192.168.1.20
Server Port:            80

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

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

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   17   8.0     17      44
Processing:     9   39   7.9     39      69
Waiting:        0   24   5.4     24      48
Total:         28   56   5.9     56     101

Percentage of the requests served within a certain time (ms)
  50%     56
  66%     58
  75%     59
  80%     60
  90%     62
  95%     64
  98%     68
  99%     75
 100%    101 (longest request)

第一次:Requests per second: 19657.71 [#/sec] (mean)

第二次:Requests per second: 17753.07 [#/sec] (mean)

5、xcache加速php
(1)安装 xcache
[root@nginx ~]# wget http://xcache.lighttpd.net/pub/Releases/3.2.0/xcache-3.2.0.tar.gz
[root@nginx ~]# tar zxf xcache-3.2.0.tar.gz 
[root@nginx ~]# cd xcache-3.2.0/
# 用 phpize 生成 configure 配置文件
[root@nginx xcache-3.2.0]# /usr/local/php5.6/bin/phpize
[root@nginx xcache-3.2.0]# ./configure  --enable-xcache  --enable-xcache-coverager --enable-xcache-optimizer --with-php-config=/usr/local/php5.6/bin/php-config
[root@nginx xcache-3.2.0]# make && make install

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

Installing shared extensions:     /usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/
(2)创建 xcache 缓存文件
[root@nginx xcache-3.2.0]# touch /tmp/xcache
[root@nginx xcache-3.2.0]# chmod 777 /tmp/xcache
(3)拷贝xcache后台管理程序到网站根目录
[root@nginx xcache-3.2.0]# cp -r htdocs/ /usr/local/nginx1.10/html/xcache
(4)配置 php 支持 xcache
[root@nginx ~]# 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 =""
6、测试

重启php-fpm

[root@nginx ~]# service php-fpm restart
Gracefully shutting down php-fpm . done
Starting php-fpm  done

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

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

[root@nginx ~]# ab -c 1000 -n 100000 http://192.168.1.20/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 192.168.1.20 (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:        192.168.1.20
Server Port:            80

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

Concurrency Level:      1000
Time taken for tests:   9.496 seconds
Complete requests:      100000
Failed requests:        0
Write errors:           0
Total transferred:      8476300000 bytes
HTML transferred:       8458600000 bytes
Requests per second:    10531.17 [#/sec] (mean)
Time per request:       94.956 [ms] (mean)
Time per request:       0.095 [ms] (mean, across all concurrent requests)
Transfer rate:          871732.00 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   14   7.4     13      58
Processing:    13   81  12.3     81     146
Waiting:        2   26   9.2     25      79
Total:         35   95  11.7     93     165

Percentage of the requests served within a certain time (ms)
  50%     93
  66%     97
  75%    100
  80%    103
  90%    110
  95%    114
  98%    124
  99%    130
 100%    165 (longest request)
 Requests per second:    10531.17 [#/sec] (mean)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章