Nginx作为高性能Web服务器,默认配置可能存在安全风险。以下是针对CentOS系统的关键安全设置,覆盖基础防护、访问控制、加密传输等方面:
http
块中添加:server_tokens off;
。add_header X-Frame-Options "SAMEORIGIN"; # 防止点击劫持
add_header X-XSS-Protection "1; mode=block"; # 启用XSS过滤
add_header X-Content-Type-Options "nosniff"; # 禁止MIME类型嗅探
add_header Referrer-Policy "strict-origin-when-cross-origin"; # 控制Referer泄露
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted.cdn.com; object-src 'none';"; # 限制资源加载
```。
limit_conn
(限制并发连接数)和limit_req
(限制请求速率)模块:limit_conn_zone $binary_remote_addr zone=addr:10m; # 定义连接数限制 zone
limit_conn addr 100; # 单个IP最大并发连接数
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=10r/s; # 定义请求速率限制 zone
limit_req zone=req_zone burst=20 nodelay; # 允许突发20个请求,无延迟
```。
.git
、.htaccess
等敏感目录,避免敏感信息泄露:location ~ /\.git { deny all; } # 禁止访问.git目录
location ~ /\.ht { deny all; } # 禁止访问.htaccess文件
```。
/admin/
)等敏感路径,仅允许特定IP段访问:location /admin/ {
allow 192.168.1.0/24; # 允许的IP段
deny all; # 拒绝其他IP
}
```。
htpasswd
工具生成密码文件:htpasswd -c /etc/nginx/.htpasswd username # 创建密码文件(首次需用-c)
Nginx配置:location /admin/ {
auth_basic "Restricted Access"; # 认证提示信息
auth_basic_user_file /etc/nginx/.htpasswd; # 密码文件路径
}
```。
server {
listen 443 ssl; # 监听443端口
server_name example.com;
ssl_certificate /path/to/cert.pem; # 证书路径
ssl_certificate_key /path/to/key.pem; # 私钥路径
ssl_protocols TLSv1.2 TLSv1.3; # 仅允许TLS 1.2及以上版本
ssl_ciphers 'HIGH:!aNULL:!MD5:!RC4:!3DES'; # 使用强加密套件
ssl_prefer_server_ciphers on; # 优先使用服务器端加密套件
}
```。
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri; # 永久重定向
}
```。
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; # HSTS,有效期1年
ssl_stapling on; # 启用OCSP Stapling
ssl_stapling_verify on; # 验证OCSP响应
```。
firewalld
限制仅允许HTTP(80)、HTTPS(443)端口访问,拒绝其他端口:sudo firewall-cmd --permanent --zone=public --add-service=http # 允许HTTP
sudo firewall-cmd --permanent --zone=public --add-service=https # 允许HTTPS
sudo firewall-cmd --reload # 重新加载防火墙规则
```。
--without-http_*
参数禁用不需要的模块(如autoindex
、rewrite
),减少攻击面。例如,禁用自动索引模块:./configure --without-http_autoindex_module ... # 编译时禁用
make && make install # 重新编译安装
```。
http
或server
块中):client_body_buffer_size 16k; # 请求体缓冲区大小
client_header_buffer_size 1k; # 请求头缓冲区大小
client_max_body_size 8m; # 最大请求体大小(限制上传文件大小)
```。
access_log /var/log/nginx/access.log; # 访问日志路径
error_log /var/log/nginx/error.log; # 错误日志路径
```。
sudo yum update nginx -y # 更新Nginx
sudo yum update openssl -y # 更新OpenSSL
```。
cp /etc/nginx/nginx.conf /etc/nginx/backup/nginx.conf.$(date +%Y%m%d) # 按日期备份
```。
以上设置需根据实际业务场景调整(如敏感路径、IP白名单范围),并定期审查日志以应对新的安全威胁。