Nginx安装配置防盗链及深度优化

发布时间:2020-03-07 17:49:19 作者:张九冫
来源:网络 阅读:683

一、编译安装前的优化
编译安装前的优化主要是用来修改程序名等等,通过更改源码以便隐藏软件名称和版本号。

下载我提供的所需源码包:https://pan.baidu.com/s/1tyS3GL0W2kcQGsdfwc3B1w
提取码:cs23
1、开始安装:

[root@nginx ~]# yum -y erase httpd        #卸载系统默认的httpd服务,防止端口冲突
[root@nginx ~]# yum -y install openssl-devel pcre-devel    #安装所需依赖
[root@nginx src]# rz          #rz命令上传所需源码包
[root@nginx src]# ls          #确认上传的源码包
nginx-sticky-module.zip    nginx-1.14.0.tar.gz    ngx_cache_purge-2.3.tar.gz
#将上传的源码包进行解压
[root@nginx src]# tar zxf nginx-1.14.0.tar.gz  
[root@nginx src]# unzip nginx-sticky-module.zip 
[root@nginx src]# tar zxf ngx_cache_purge-2.3.tar.gz 
[root@nginx src]# cd nginx-1.14.0/        #切换至nginx目录
[root@nginx nginx-1.14.0]# vim src/core/nginx.h    #修改以下两行配置
#define NGINX_VERSION      "6.6"       #这里是修改nginx的版本号
#define NGINX_VER          "IIS/" NGINX_VERSION    #这里修改的是软件名称,我将原有的nginx改为了IIS。
#修改后,保存退出即可
[root@nginx nginx-1.14.0]# vim src/http/ngx_http_header_filter_module.c   #编辑该文件
#修改前如下:
static u_char ngx_http_server_string[] = "Server: nginx" CRLF;     #第49行
#修改后如下:
static u_char ngx_http_server_string[] = "Server: IIS" CRLF;   #该IIS和前一个文件更改的最好一致。
#更改完成后,保存退出即可。
[root@nginx nginx-1.14.0]# vim src/http/ngx_http_special_response.c   #修改此配置文件,防止页面出现错误时,回显时带着nginx和版本号
#修改前如下:
static u_char ngx_http_error_tail[] =     #在此之前有一行与此非常相似,注意区分,这行的error后面没有build字样。
"<hr><center>nginx</center>" CRLF           #第36行
"</body>" CRLF
"</html>" CRLF
#更改后如下:
static u_char ngx_http_error_tail[] =
"<hr><center>IIS</center>" CRLF       #将原有的nginx改为IIS
"</body>" CRLF
"</html>" CRLF
#更改完成后,保存退出即可
[root@nginx nginx-1.14.0]# useradd -M -s /sbin/nologin www   #创建nginx运行用户
[root@nginx nginx-1.14.0]# ./configure --prefix=/usr/local/nginx1.14 --user=www --group=www --with-http_stub_status_module  --with-http_realip_module  --with-http_ssl_module --with-http_gzip_static_module  --http-client-body-temp-path=/var/tmp/nginx/client --http-proxy-temp-path=/var/tmp/nginx/proxy  --http-fastcgi-temp-path=/var/tmp/nginx/fcgi --with-pcre  --add-module=/usr/src/ngx_cache_purge-2.3  --with-http_flv_module --add-module=/usr/src/nginx-sticky-module --with-http_dav_module --with-http_addition_module --with-http_sub_module --with-http_mp4_module && make && make install
#编译安装
[root@nginx nginx-1.14.0]# ln -sf /usr/local/nginx1.14/sbin/nginx /usr/local/sbin/  #创建nginx命令软连接
[root@nginx nginx-1.14.0]# mkdir -p /var/tmp/nginx/client      #创建存放临时文件目录
[root@nginx nginx-1.14.0]# nginx -t       #检查配置文件
[root@nginx nginx-1.14.0]# nginx       #没有错误后,启动nginx
[root@nginx nginx-1.14.0]# netstat -anput | grep 80      #确定80端口处于监听状态

命令行验证http头部的软件名称及版本号是否更改:

[root@nginx conf]# curl -I 127.0.0.1     #访问本机
HTTP/1.1 200 OK
Server: IIS/6.6             #OK,使我们更改的名称及版本
Date: Fri, 25 Oct 2019 00:10:17 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Fri, 25 Oct 2019 00:03:52 GMT
Connection: keep-alive
ETag: "5db23be8-264"
Accept-Ranges: bytes
[root@nginx conf]# curl -I 127.0.0.1/a.html       #访问一个不存在的页面
HTTP/1.1 404 Not Found
Server: IIS/6.6           #错误页面回显的信息,也是我们更改的,OK
Date: Fri, 25 Oct 2019 00:11:07 GMT
Content-Type: text/html
Content-Length: 164
Connection: keep-alive

二、Nginx配置项优化
Nginx是master/worker结构:一个master进程,生成一个或多个worker进程。示意图如下:
Nginx安装配置防盗链及深度优化
master-worker设计模式主要包含两个主要组件:master和worker,master维护着worker队列,将请求下发到多个worker并执行,worker主要进行实际逻辑计算,并将结果返回给master。

Nginx采用这种进程模型的好处在于采用独立的进程,可以让互相之间不会影响,一个进程退出后,其他进程还在工作,服务不会中断,master进程则很快重新启动新的worker进程。当worker发生异常时,会导致当前worker上的所有请求失败,而不会影响到其他worker进程。
接下来的所有配置参数都是在Nginx配置文件的全局中写入

1、调整Nginx运行工作进程个数

[root@nginx ~]# vim /usr/local/nginx1.14/conf/nginx.conf    #编辑主配置文件
 worker_processes  4;    #一般设置为CPU的核心或者核心数x2
  [root@nginx ~]# nginx -s reload          #重启Nginx服务
  [root@nginx ~]# ps -ef | grep nginx | grep worker    #查看开启的worker进程
  www      128282   6761  0 11:41 ?        00:00:00 nginx: worker process
  www      128283   6761  0 11:41 ?        00:00:00 nginx: worker process
  www      128284   6761  0 11:41 ?        00:00:00 nginx: worker process
  www      128285   6761  0 11:41 ?        00:00:00 nginx: worker process

2、Nginx运行CPU亲和力

[root@nginx ~]# vim /usr/local/nginx1.14/conf/nginx.conf   <!--编辑主配置文件-->
<!--如果是四核配置,应配置如下:-->
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
       <!--
上面是每个核心开启一个worker,若要每个核心对应两个worker,
则需要写入:worker_cpu_affinity 0001 0010 0100 1000 0001 0010 0100 1000;
                                 -->
<!--  如果是八核配置,则应配置如下:  -->
worker_processes 8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000
10000000;
worker_rlimit_nofile 65535;      <!--修改nginx最多可以打开的文件数-->
         <!--   
        这个配置是指当一个nginx进程打开的最多文件描述数目,理论值应该是系统最多打开文件数(使用ulimit -n命令查看)与nginx进程相除,但是nginx分配请求并不是那么均匀,所以最好与命令ulimit -n得到的值保持一致。
在上面指定了其值为“65535”但是系统默认是1024,怎么办呢?  
                               -->
[root@docker ~]# ulimit -n       <!--确定系统最对打开文件数-->
1024
<!--如果此时启动nginx服务,是会出现异常的。-->
[root@docker ~]# vim /etc/security/limits.conf   <!--编辑此文件,以便修改系统默认的文件数-->
<!--在配置文件末尾增加以下字段 -->
*       soft    nofile  65535
*       hard    nofile  65535
<!--更改完成后,保存退出-->
[root@nginx conf]# su -      <!--重新登录,以便生效-->
[root@nginx ~]# ulimit -n       <!-- 再次查看确认是否修改成功-->
65535
[root@nginx ~]# nginx -s reload        <!--重启nginx服务,以便配置生效-->

worker_processes最多开启8个,8个以上的话性能不会再提升了,而且稳定性变得更低,所以8个进程足够用了。
由于接下来是对配置文件增加一些配置项,就直接写配置项及解释了

3、Nginx事件处理模型

#配置文件修改如下:
events {
    use epoll;
    worker_connections  65535;
    multi_accept on;
}

nginx 采用 epoll 事件模型,处理效率高,work_connections 是单个 worker 进程允许客户端最大连接数,这个数值一般根据服务器性能和内存来制定,Nginx服务器的实际并发量就是 worker 进程数乘以 work_connections,填入一个 65535,则表示其并发量可以达到了65535 x 4 = 262140的一个并发量,一个网站的并发达到这么大的数量,也算是一个大站了!
multi_accept 是告诉 nginx 收到一个新连接通知后接受尽可能多的连接。

注:接下来的所有配置都将在http{ }模块中写入。
4、开启高效传输模式

http {
    include       mime.types;
    default_type  application/octet-stream;
         ........................#省略部分内容
    sendfile        on;        #此行默认开启
    tcp_nopush     on;     #去掉此行开头的注释符号

上述配置的相关解释如下:

5、连接超时时间
修改及增加下面的内容主要目的是保护服务器资源,CPU,内存,控制连接数,因为建立连接也是需要消耗资源的。

#在http{  }字段增加以下内容:
    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;

6、fastcgi优化
Fastcgi (快速通用网关接口)是静态服务和动态服务的一个接口,Cache表示写入缓存区,Buffer表示读取缓存区。

在生产环境中,还需要根据自己公司的网站来决定,是否需要开启动态页面的缓存功能,毕竟动态页面变化比较快,大多数情况下,我们都不会开启动态页面的缓存。

#以下配置写入在http{  }字段内
    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;

上述配置项解释如下:

总结:

  1. nginx 的缓存功能有:proxy_cache / fastcgi_cache
  2. proxy_cache 的作用是缓存后端服务器的内容,可能是任何内容,包括静态的和动态。
  3. fastcgi_cache 的作用是缓存 fastcgi 生成的内容,很多情况是 php 生成的动态的内容。
  4. proxy_cache 缓存减少了 nginx 与后端通信的次数,节省了传输时间和后端宽带。
  5. fastcgi_cache缓存减少了nginx与php的通信的次数,更减轻了php和数据库(mysql)的压力。

7、gzip调优

#以下配置项在http{  }字段中写入:
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:开启压缩功能;

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

   server {
        listen       80;
        server_name  localhost;
                ................#省略部分内容
        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 中记录不存在的错误,默认on。

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

9、配置防盗链
防盗链的作用就是防止别人直接从你网站引用图片等链接,消耗了我们的资源和网络流量,而我们没有得到任何好处,吃力不讨好。

解决办法有以下几种:
1:水印,品牌宣传,你的带宽,服务器足够 ;
2:防火墙,直接控制,前提是你知道 IP 来源 ;
3:防盗链策略。

下面的方法是直接给予 404 的错误提示或者跳转到指定提示页面。

#以下配置写在server{  }字段中:
        location ~* ^.+\.(jpg|gif|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
            valid_referers none blocked www.test.com test.com;    #该字段是指定允许跳转访问的域名
            if ($invalid_referer) {
            #return 302 http://www.test.com/img/nolink.png;   #该注释的配置项表示可以将其重定向到指定文件
            return 404;          #这里是直接返回给客户端状态码404
            break;
            }
            access_log off;         #关闭访问日志
          }
        location / {            #防盗链配置必须写在所有location字段之前
            root   html;
            index  index.html index.htm;
        }
#在重定向到另一个文件时,需要特别注意其后缀不能匹配防盗链规则,否则客户端会得到“重定向次数过多的”提示。
#我这里先选择返回状态码404

以上修改后的完整配置文件如下:


#user  nobody;
worker_processes  4;
worker_cpu_affinity 0001 0010 0100 1000;
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.20.5 www.test.com;
            if ($invalid_referer) {
            return 302 http://192.168.20.5/img/nolink.png;
            #return 404;
            break;
            }
            access_log off;
          }
        location / {
            root   html;
            index  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;
        }
        ......................#省略后面的注释内容

10、内核参数优化

[root@nginx conf]# 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 conf]# sysctl -p       #刷新,使内核修改生效,正常的话,会返回所有配置项
#刷新后,所有配置项都会以文件的形式写入某个目录下,可以指定find命令进行查找验证
#如要寻找“net.core.netdev_max_backlog”对应的文件,则可以执行命令“find / -name netdev_max_backlog”进行查找

11、关于系统连接数的优化
linux系统中,open files的默认值 为 1024,说明服务器只允许同时打开 1024 个文件,使用命令 ulimit -a 可以查看当前系统的所有限制值,使用命令 ulimit -n 可以查看当前的最大打开文件数。
新装的 linux 默认只有 1024 ,在负载较大的服务器上,很容易遇到 error: too many open files。因此,需要将其改大。

[root@nginx core]# vim /etc/security/limits.conf     #修改此配置文件
#在文件的末尾增加以下字段:
*       soft    nofile  65535
*       hard    nofile  65535
*       soft    noproc  65535
*       hard    noproc  65535
#添加完成后,用户需重新登录,以便更改生效。
[root@nginx ~]# bash
[root@nginx ~]# ulimit -a     #查看是否生效

三、验证上述优化及Nginx服务器压力测试
1、测试防盗链功能:
准备两台服务器,一台是刚才优化的Nginx服务器,另一台随意,可以提供web功能即可。

刚才优化过的Nginx服务器IP地址为192.168.20.5,另一台服务器的IP地址为:192.168.20.2。

1)Nginx服务器配置如下:

[root@nginx html]# ls         <!--nginx服务器的网页根目录如下-->
50x.html  index.html  test.png
[root@nginx html]# vim ../conf/nginx.conf        <!--其防盗链配置如下-->
    ......................#省略部分内容
location ~* ^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
            valid_referers none blocked 192.168.20.5 www.test.com;
            if ($invalid_referer) {
            #return 302 http://192.168.20.5/img/nolink.png;
            return 404;
            break;
            }
            access_log off;
          }
    ......................#省略部分内容
<!--根据其防盗链配置,客户端如果通过另一台服务器提供的链接访问该服务器的资源,将会得到404状态码--> 
[root@nginx html]# nginx -s reload      #重启Nginx服务器,使防盗链配置生效

2)第二台服务器的网页文件如下:

[root@daolian html]# cat index.html      #其超链接地址指向了第一台Nginx服务器的test.png图片
<a href="http://192.168.20.5/test.png">lianjie</a>

3)客户端直接访问Nginx服务器的话,会看到test.png的页面如下:

Nginx安装配置防盗链及深度优化
4)客户端访问第二台服务器测试:
Nginx安装配置防盗链及深度优化
点击超链接后,会看到以下页面:
Nginx安装配置防盗链及深度优化
5)现在换另一种防盗链规则,再次进行测试:

[root@nginx html]# vim ../conf/nginx.conf        #编辑其配置文件
        location ~* ^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
            valid_referers none blocked 192.168.20.5 www.test.com;
            if ($invalid_referer) {
            return 302 http://192.168.20.5/img/nolink.png;     #将其重定向到img目录下的nolink.png图片
            #return 404;     #将返回404状态码注释掉
            break;
            }
            access_log off;
          }
[root@nginx html]# nginx -s reload      #重启使配置生效
[root@nginx img]# ls /usr/local/nginx1.14/html/img     #重定向的目录下文件如下:
nolink.png

6)客户端再次点击超链接进行测试,会看到如下页面:
Nginx安装配置防盗链及深度优化
2、压力测试
对网页的静态页面和php动态页面都进行压力测试的话,需要安装部署LNMP架构,这里采用单台部署的方式,部署过程请参考文档:https://blog.51cto.com/14227204/2435795
,若只是用来做压力测试,MySQL数据库可以不安装。

部署LNMP架构过程略...

部署完成后,需要更改配置文件:

[root@nginx html]# vim ../conf/nginx.conf      #编辑主配置文件
#在server{  }字段中添加以下内容
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.conf;
        }
[root@nginx html]# pwd
/usr/local/nginx1.14/html
[root@nginx html]# cat test.php      #网页根目录下test.php文件内容如下:
<?php
phpinfo();
?>

完成后,需要确保访问192.168.20.5/test.php时可以看到以下页面:
Nginx安装配置防盗链及深度优化
1)开始测试:

[root@nginx ~]# ab -c 500 -n 50000 127.0.0.1/index.html
#测试静态页面性能,一次请求500个数,共请求50000个数。
Requests per second:    2407.58 [#/sec] (mean)     #Nginx服务器的吞吐量
#我们主要关注的是上述的返回信息,也就是Nginx服务器的吞吐量
#服务器性能越好,吞吐量越高
[root@nginx html]# ab -c 100 -n 1000 127.0.0.1/test.php    #根据服务器性能选择相应的数值
推荐阅读:
  1. Nginx安装及深度优化(3)
  2. Nginx深度优化

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

防盗链 深度优化 nginx

上一篇:基于WRITESET的并行复制方式

下一篇:初学python的一些基础知识

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》