自己使用 nginx 的时候,都是用最简配置。如果是企业应用场景,应该怎么做?
前言
可以从一下几个方面入手
一、安全方面
- 隐藏 nginx header 版本号
- 更改源码,隐藏 nginx 软件名称
- 更改 nginx 默认用户及用户组
- nginx 站点目录及文件 URL 访问控制(防止恶意解析)
- 防止恶意解析访问企业网站
- 配置 nginx 图片及目录防盗链
- 配置 nginx 防爬虫
- 限制 HTTP 请求方法
- 防 DDOS 攻击
二、性能方面
- 根据 CPU 逻辑核心数,配置 nginx worker 进程个数
- 配置 nginx worker 进程的 CPU 亲和力参数
- 配置 ngixn worker 单个进程允许的客户端最大连接数
- 配置 nginx worker 进程的最大打开文件数
- 配置 nginx 事件处理模型为 epoll
三、HTTP 协议方面
- 开启高效的文件传输模式(sendfile/tcp_nopush/tcp_nodelay)
- 设置连接超时时间
- 设置客户端上传文件大小
- fastcgi 调优
四、功能方面
- 配置 nginx gzip 压缩功能
- 配置 nginx expires 缓存功能
- 配置 nginx 错误页面的优雅显示
五、日志方面
- 每天进行日志切割、备份/不记录不需要的访问日志/访问日志的权限设置
六、架构方面
- nginx 程序架构优化(服务解耦)
- 使用 CDN 为网站内容加速
接下来进行具体说明
一、安全方面
1. 隐藏 nginx header 版本号
没有隐藏版本号时,使用 Chrome 浏览器访问 nginx,可以在开发者工具中看到 Header
的 Server
的内容为

不同版本的 nginx 有不同的漏洞,如果知道了版本号,容易让别人根据版本对 nginx 进行攻击,因此应该隐藏 nginx 的版本号
打开 nginx.conf
,在 http
部分添加以下内容
1 | # 省略... |
然后重启 nginx,再次使用 Chrome 浏览器访问 nginx。可以看到 nginx 的版本号已经没有了

2. 更改源码,隐藏 nginx 软件名称
隐藏 nginx 的版本号还是不够彻底,如果把 nginx 的名称改成其他的,可以更加迷惑黑客。把软件名改成 Apache 或者 IIS 都行,不过 IIS 更好。因为 IIS 只能安装在 Windows 平台。那么入侵者看到了 IIS 就以为服务器是 Windows 系统,那么它使用的漏洞工具就只针对 Windows,但实际上服务器是 Linux,这样黑客就更迷惑了
打开 src/core/nginx.h
,修改 nginx 的版本号和版本名称,假装是 Microsoft-IIS/8.5
1 |
然后再重新编译安装 nginx。现在访问 nginx 之后,Header
中的 Server
内容变了

3. 更改 nginx 默认用户及用户组
不要用 root 权限来运行 nginx,否则黑客拿到的 WebShell 权限很可能是 root 权限
创建用户组
1 | $ groupadd nginx |
创建一个用户,禁止ssh登录,且不创建 home 目录
1 | $ useradd -s /sbin/nologin -M nginx |
然后修改 nginx.conf
1 | user nginx nginx; # 前面是用户,后面是用户组 |
在编译安装的时候也可以指定用户与用户组
1 | $ ./configure --prefix=/usr/local/nginx-1.12.2 --user=nginx --group=nginx |
现在运行 ps aux | grep nginx
查看 nginx 的进程信息
1 | root@ikutarian:~# ps aux | grep nginx |
可以看到 Nnginx 的 worker
进程的用户是 nginx
使用 limit_except 指令来实现
1 | server { |
注意:允许了 GET
请求,意味着也允许了 HEAD
请求
- 防 DDOS 攻击
nginx