参考资料

  1. Nginx用户cookie模块详细说明以及案例
  2. Nginx配置文件中通过location块匹配静态资源类型,并添加缓存响应头
  3. Nginx error_log:错误日志配置详细说明以及案例
  4. PHP-FPM 性能优化
  5. Nginxtry_files 文件判断指令详细说明以及案例
  6. nginx 配置多个server
  7. Nginx在Web开发中的应用
  8. nginx遇到攻击时如何快速响应?

以下是Nginx主要的安全相关模块及其配置示例:


1. ngx_http_access_module(IP访问控制)

功能:基于IP地址限制访问。
示例

location /admin {
    allow 192.168.1.0/24;  # 允许192.168.1.0/24网段访问
    deny all;              # 拒绝其他所有IP
}

2. ngx_http_auth_basic_module(HTTP基本认证)

功能:要求用户输入用户名和密码才能访问资源。
示例

location /secure {
    auth_basic "Restricted Area";  
    auth_basic_user_file /etc/nginx/.htpasswd;  # 密码文件路径
}

生成密码文件

htpasswd -c /etc/nginx/.htpasswd username

3. ngx_http_ssl_module(HTTPS加密)

功能:启用SSL/TLS加密通信。
示例

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;
    
    # 推荐的安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
}

4. ngx_http_limit_req_module(请求速率限制)

功能:防止DDoS/暴力破解攻击。
示例

limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;

server {
    location /api {
        limit_req zone=req_limit burst=20 nodelay;
    }
}
  • rate=10r/s:每秒最多10个请求

  • burst=20:允许短时突发20个请求


5. ngx_http_limit_conn_module(连接数限制)

功能:限制单个IP的并发连接数。
示例

limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

server {
    location /download {
        limit_conn conn_limit 5;  # 每个IP最多5个并发连接
    }
}

6. ngx_http_referer_module(防盗链)

功能:防止其他网站盗用资源(如图片)。
示例

location ~* \.(jpg|png|gif)$ {
    valid_referers none blocked example.com *.example.com;
    if ($invalid_referer) {
        return 403;
    }
}

7. ngx_http_headers_module(安全HTTP头)

功能:添加安全相关的HTTP响应头。
示例

server {
    add_header X-Frame-Options "SAMEORIGIN";  # 防止点击劫持
    add_header X-Content-Type-Options "nosniff";  # 禁止MIME类型嗅探
    add_header Content-Security-Policy "default-src 'self'";  # CSP策略
}

8. ngx_http_secure_link_module(安全链接)

功能:生成有时效性的加密链接(如文件下载)。
示例

location /protected {
    secure_link $arg_md5,$arg_expires;
    secure_link_md5 "$secure_link_expires$uri secret_key";

    if ($secure_link = "") {
        return 403;  # 链接无效或过期
    }
}

生成链接的脚本示例(Python):

import hashlib, time
expires = int(time.time()) + 3600  # 1小时后过期
token = hashlib.md5(f"{expires}/protected secret_key".encode()).hexdigest()
url = f"/protected?md5={token}&expires={expires}"

9. ngx_http_realip_module(获取真实IP)

功能:在反向代理环境下获取客户端真实IP。
示例

set_real_ip_from 10.0.0.0/8;  # 信任的代理服务器IP段
real_ip_header X-Forwarded-For;
real_ip_rec