首页 > 技术文章 > nginx常用优化

CMX_Shmily 2019-09-17 08:57 原文

隐藏Nginx版本号!(重点)

在生产环境中,需要隐藏 Nginx 的版本号,以避免安全漏洞的泄漏

一旦有黑客知道Nginx版本号便可以利用Nginx漏洞进行攻击,严重影响到了公司的安全

查看隐藏版本号命令:curl -I http://ip地址

========================================================

安装Nginx后查看:

[root@localhost nginx-1.16.0]# curl -I http://192.168.200.120
HTTP/1.1 200 OK
Server: nginx/1.16.0
Date: Thu, 12 Sep 2019 03:55:10 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 12 Sep 2019 01:08:46 GMT
Connection: keep-alive
ETag: "5d799a9e-264"
Accept-Ranges: bytes

隐藏方法1【基于源码包】:(安装Nginx后要修改文件必须先卸载Nginx再安装)

[root@localhost ~]# killall -9 nginx                                            //杀死nginx进程
[root@localhost ~]# rm -rf /usr/local/nginx/     
[root@localhost ~]# cd /usr/src/nginx-1.16.0/
[root@localhost nginx-1.16.0]# make clean
rm -rf Makefile objs                                                                
[root@localhost nginx-1.16.0]# cd
[root@localhost ~]# rm -rf /usr/src/nginx-1.16.0/                    //卸载完成

[root@localhost ~]# tar xf nginx-1.16.0.tar.gz -C /usr/src

[root@localhost ~]# cd /usr/src/nginx-1.16.0/

[root@localhost nginx-1.16.0]# vim src/core/nginx.h

修改文件前图示:

修改文件后图示:

[root@localhost nginx-1.16.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module

[root@localhost nginx-1.16.0]# make

[root@localhost nginx-1.16.0]# make install

[root@localhost nginx-1.16.0]# curl -I http://192.168.200.120
curl: (7) Failed connect to 192.168.200.120:80; 拒绝连接
[root@localhost nginx-1.16.0]# netstat -anpt | grep nginx
[root@localhost nginx-1.16.0]# nginx
[root@localhost nginx-1.16.0]# netstat -anpt | grep nginx
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 21446/nginx: master 
[root@localhost nginx-1.16.0]# curl -I http://192.168.200.120
HTTP/1.1 200 OK
Server: apache/2.4.31
Date: Thu, 12 Sep 2019 04:15:38 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 12 Sep 2019 04:13:25 GMT
Connection: keep-alive
ETag: "5d79c5e5-264"
Accept-Ranges: bytes

 方法2【修改配置文件】(不卸载Nginx隐藏版本号,直接修改配置文件)

[root@localhost nginx-1.16.0]# curl -I http://192.168.200.115                           
HTTP/1.1 200 OK  
Server: nginx/1.16.0                                                                               //原版本号
Date: Thu, 12 Sep 2019 05:38:07 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 12 Sep 2019 05:37:35 GMT
Connection: keep-alive
ETag: "5d79d99f-264"
Accept-Ranges: bytes

[root@localhost nginx-1.16.0]# vim /usr/local/nginx/conf/nginx.conf

在sendfile on;后添加一行命令:

server_tokens off;

[root@localhost nginx-1.16.0]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

[root@localhost nginx-1.16.0]# killall -HUP nginx                                     //重新加载配置
[root@localhost nginx-1.16.0]# curl -I http://192.168.200.115                  
HTTP/1.1 200 OK
Server: nginx                                                                                            //修改后的版本号
Date: Thu, 12 Sep 2019 05:45:43 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 12 Sep 2019 05:37:35 GMT
Connection: keep-alive
ETag: "5d79d99f-264"
Accept-Ranges: bytes

 

修改Nginx用户和组!

Nginx 运行时进程需要有用户与组的支持,以实现对网站文件读取时进行访问控制。
Nginx 默认使用 nobody 用户账号与组账号,一般也要进行修改。

========================================================

1:编译安装时指定

[root@localhost conf]# useradd -M -s /sbin/nologin nginx

[root@localhost nginx-1.16.0]# tail -l /etc/passwd;tail -l /etc/group

[root@localhost ~]# tar xf nginx-1.16.0.tar.gz -C /usr/src
[root@localhost ~]# cd /usr/src/nginx-1.16.0/

[root@localhost nginx-1.16.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module && make && make install

2:修改配置文件

[root@localhost nginx-1.16.0]# vim /usr/local/nginx/conf/nginx.conf

修改:

user  nginx nginx;               
worker_processes  2;

[root@localhost nginx-1.16.0]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost nginx-1.16.0]# killall -s HUP nginx
nginx: no process found
[root@localhost nginx-1.16.0]# nginx
[root@localhost nginx-1.16.0]# killall -s HUP nginx
[root@localhost nginx-1.16.0]# ps -aux | grep nginx
root 22334 0.0 0.2 151560 5068 pts/1 T 13:33 0:00 vim /usr/local/nginx/conf/nginx.conf
root 25663 0.0 0.0 20692 1392 ? Ss 14:40 0:00 nginx: master process nginx
nginx 25667 0.0 0.0 23208 1488 ? S 14:40 0:00 nginx: worker process
nginx 25668 0.0 0.0 23208 1488 ? S 14:40 0:00 nginx: worker process
root 25678 0.0 0.0 112724 992 pts/1 S+ 14:41 0:00 grep --color=auto nginx

 

 配置nginx查看用户访问量:

编译时启用--with-http_stub_status_module模块:

[root@localhost ~]#./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module && make && make install

主配置文件加入:

[root@localhost conf]# vim nginx.conf

location /status {
      stub_status on;
      access_log off;
}

 

 

配置Nginx网页缓存时间!(重点

当 Nginx 将网页数据返回给客户端后,可设置缓存的时间,以方便在日后进行相同内容
的请求时直接返回,以避免重复请求,加快了访问速度,一般针对静态网页进行设置,对动
态网页不用设置缓存时间。可在 Windows 客户端中使用 fiddler 查看网页缓存时间。
设置方法:
在 可修改配置文件,在 http 段、或 server 段、或者 location 段加入对特定内容的过期参
数。

====================================================================

[root@localhost html]# vim /etc/nginx.conf 


user nginx nginx;
worker_processes 2;


error_log logs/error.log;
error_log logs/error.log info;


pid logs/nginx.pid;



events {
       use epoll;
       worker_connections 10240;
}

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;
         server_tokens off;
         keepalive_timeout 65;


server {
        listen 80;

        server_name localhost;

         charset utf-8;


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

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {            
            expires      30d;        
        }        
        location ~ .*\.(js|css)?$ {              
            expires      1h;        
        } 


error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
     }

   }

}

[root@localhost nginx-1.16.0]# cd
[root@localhost ~]# cd /usr/local/nginx/html/

导入图片
[root@localhost html]# rz
z waiting to receive.**B0100000023be50
[root@localhost html]# ls
50x.html index.html linux.jpg

[root@localhost html]# vim index.html

在尾部添加如下代码:

<p><em>Thank you for using nginx.</em></p>
<img src='linux.jpg'/>
</body>
</html>
~                 

[root@localhost html]# killall -s HUP nginx                           //重启配置

 

 

Nginx为目录添加访问控制!

用户访问控制:使用apache的htpasswd来创建密码文件!

因为nginx没有创建密码文件的指令,所以必须利用apache下的一个叫htpasswd(httpd-tools)来创建密码文件,

但是不能开启httpd服务,避免httpd服务与nginx服务抢占80端口

虚拟机IP:192.168.200.115

第一步:安装httpd-tools服务

[root@localhost ~]# yum -y install httpd-tools

[root@location ~]#cd /usr/local/nginx/conf

第二步:创建一个文件用于接收用户及密码

[root@location conf]#touch user.txt

[root@localhost conf]# htpasswd -c /usr/local/nginx/conf/user.txt tom
New password: 123123
Re-type new password: 123123
Adding password for user tom

[root@localhost conf]# cat /usr/local/nginx/conf/ user.txt
tom:$apr1$JmLhDuwD$GPM8zM504TP9F0eDfHT101

第三步:修改主配置文件(摘要认证)

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

在server下再添加一个location如下命令

location /tom { stub_status on; access_log off; auth_basic "Nginx Tom"; auth_basic_user_file /usr/local/nginx/conf/user.txt; }

在网页中输入192.168.200.115/tom

 

 

客户端访问控制!

 allow 192.168.200.0/24;          允许192.168.200.0的网段访问

 deny  192.168.200.0/24;          禁止192.168.200.0的网段访问

 

实现Nginx的日志分割!(重点)

时间越久内存占用率越高,高并发量,会给服务器带来巨大的缓存压力

解决方法:创建一个新的目录,设置周期性计划定期的将旧目录里面的日志移动到新目录中,一般只保存30天内,30天后一律删除

[root@localhost ~]# date "+%Y%m%d"                                  //今天的时间
20190913
[root@localhost ~]# date -d "-1 day" "+%Y%m%d"                //昨天的时间
20190912

=====================================================================================

[root@localhost ~]# vim /opt/cut_nginx_log.sh

#!/bin/bash
#cut_nginx_log.sh

datetime=$(date -d "-1 day" "+%Y%m%d")        //时间,date -d "-1 day"代表日期减1
log_path="/usr/local/nginx/logs"             //日志的存放位置
pid_path="/usr/local/nginx/logs/nginx.pid"   //进程的PID号,有PID号代表 进程还活着
[ -d $log_path/backup ] || mkdir -p $log_path/backup   //如果$log_path/backup不是一个目录则创建$log_path/backup目录
if [ -f $pid_path ]                                //如果$pid_path是一个文件
then
mv $log_path/access.log $log_path/backup/access.log-$datetime  //那么移动旧日志的文件到新目录下以此来实现分割
kill -USR1 $(cat $pid_path)                                    //USR1代表信号,他会给进程传一个信号让进程生成一个新的日志
find $log_path/backup -mtime +30 | xargs rm -f                //查找30天前的日志并删除
else
echo "Error,Nginx is not working!" | tee -a /var/log/messages  //否则提示nginx is not working且追加到日志中
fi

[root@localhost ~]# chmod +x /opt/cut_nginx_log.sh 
[root@localhost ~]# bash /opt/cut_nginx_log.sh 
[root@localhost ~]# cd /usr/local/nginx/logs/
[root@localhost logs]# ls
access.log   backup  error.log  nginx.pid
[root@localhost logs]# ls backup/
access.log-20190912

[root@localhost ~]# crontab -e
crontab: installing new crontab
[root@localhost ~]# crontab -l
0    0   *    *    *     bash /opt/cut_nginx_log.sh            //每月每周每天的0时0分执行脚本     

当未运行时!

[root@localhost logs]# killall -9 nginx
[root@localhost logs]# bash /opt/cut_nginx_log.sh 
/opt/cut_nginx_log.sh: 第 11 行:kill: (8282) - 没有那个进程
[root@localhost logs]# rm -rf /usr/local/nginx/logs/nginx.pid 
[root@localhost logs]# bash /opt/cut_nginx_log.sh 
Error,Nginx is not working!

 

配置Nginx实现连接超时及修改进程数!

在企业网站中,为了避免同一个客户长时间占用连接,造成资源浪费,可以设置相应的
连接超时参数,实现控制连接访问时间。
keepalived_timeout :设置连接保持超时时间,一般可只设置该参数,默认为 75 秒,可根据
网站的情况设置,或者关闭,可在 http 段、server 段、或者 location 段设置。
client_header_timeout :指定等待客户端发送请求头的超时时间。
client_body_timeout :设置请求体读超时时间。
若出现超时,会返回 408 报错

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

在http中添加如下三条命令
keepalive_timeout  65; //等待请求时间为65秒、超过65秒服务器自动断开连接
client_header_timeout 60; //等待客户端的头部超时时间为60秒
client_body_timeout 60; //等待客户端的主体超时时间为60秒

 [root@localhost ~]# killall -s HUP nginx

===================================================================

在高并发场景,需要启动更多的 nginx 进程以保证快速影响,以处理用户的请求,避免
造成阻塞

修改配置文件的 worker_processes  参数,一般设置为 CPU  的个数或者核数的 2  倍

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

worker_processes  2;                             //cpu核数

worker_cpu_affinity 0001 0010             //cpu分配

 

配置Nginx实现网页压缩功能!

Nginx的nginx_http_gzip_module压缩提供了对文件内容进行压缩的功能,允许Nginx服务器将输出内容2发送到客户端之前进行压缩,这样文件内容变小传输速度变快,以便于节约网站的带宽,提升用户体验,模块默认已经安装!

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

 gzip on;
    #gzip _min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types text/plain text/javascript application/x-javascrip t text/css text/xml
application/xml application/xml+rss;

[root@localhost ~]# nginx -t

[root@localhost ~]# killall -s HUP nginx

 


 

 

配置Nginx实现防盗链功能!及Nginx Rewrite规则(重点)

准备两台Linux,用第二台linux主机来通过拿第一台主机的图片链接来展现图片;

因为主机2是通过主机1拿的图片链接所以当别人都通过链接访问图片时,占用的是主机一的内存空间,而不是占用主机2的内存空间

A)设定主机一为本公司的服务器,一旦非本公司人员通过链接去访问图片时,会对服务器造成内存压力。因此要设置非本公司人员不能通过链接访问。

此处用的是域名方式

解决方法,主机一做防盗链功能可以有效的阻止非本公司人员访问图片。以造成内存压力-------》这样主机2将访问不到图片即使有图片链接

第一台Ip地址为:192.168.200.115

 

第二台ip地址值为:192.168.200.105

未添加图片前只有字母:

改动index.html添加图片:

[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# ls
50x.html    index.html
[root@localhost html]# vim index.html

在p段落下添加图片链接
<img src="http://192.168.200.115/linux.jpg" />

添加图片后



在主机1中的server下添加如下命令

[root@localhost ~]# vim /usr/local/nginx/html/error.txt

<h1>盗链可耻</h1>

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

location ~* \.(jpg|gif|png|swf)$ {
      #*.amber.com amber.com相当于公司域名
      expires 1d;
      root html;
      valid_referers none blocked *.source.com source.com;
      if ($invalid_referer) {
      rewrite ^/ http://www.source.com/error.txt;
   }
}

error_page 500 502 503 504 /50x.html;
     location = /50x.html {
     root html;
    }

   }
}

[root@localhost ~]# killall -9 nginx                             //杀死nginx进程
[root@localhost ~]# nginx                                          //开启nginx进程
[root@localhost ~]# killall -HUP nginx                      //重新加载

================================================================================

真机改动hosts文件:hosts文件所在(C盘中windows、system32、drivers、etc中)

文件内容改动如下:

192.168.200.115 www.source.com
192.168.200.105 www.steal.com

=================================================================================

主机一、主机二浏览器访问对比

www.source.com页面需要强制刷新按(shift+fn+f5)

 

www.sttal.com页面需要强制刷新按(shift+fn+f5)

 =====================================================================================

自定义错误页面

[root@localhost ~]#vim /etc/hosts

192.168.200.115 www.source.com

 

第一步:自定义错误页面需先准备好错误图片(这里定义error.jgp图片)

第二步:修改主配置文件:

[root@localhost html]# ls
40x.html      50x.html      error.jpg       index.html      linux.jpg     trror.txt

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

添加如下命令,这是一个自定义的404 401 403 408错误页面且

error_page 403 404 401 408 /40x.html; //一旦页面报404 401 403 408错误让他去寻找40x.html
location = /40x.html {           //location匹配40x.html找html
root html;
}

结果如图所示:

 

推荐阅读