Nginx生产环境配置示例

Linux

# Linux生产环境配置
# 自动设置为CPU核心数,充分利用多核性能(通常为核心数或核心数*2)
worker_processes auto;

# 定义错误日志位置和级别(Linux标准路径)
error_log /var/log/nginx/error.log warn;
# 指定PID文件位置(Linux常见位置)
pid /var/run/nginx.pid;

events {
    # Linux下可支持更高并发连接,根据系统资源调整(ulimit -n)
    worker_connections 4096;
    
    # Linux高性能事件模型,使用epoll(必选)
    use epoll;
    
    # 优化连接接受方式,尽可能多地接受新连接
    multi_accept on;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    # Linux性能优化套件
    sendfile on;
    tcp_nopush on;       # 与sendfile配合,优化数据包发送
    tcp_nodelay on;      # 禁用Nagle算法,降低小数据包延迟
    types_hash_max_size 2048;
    
    # 安全:隐藏Nginx版本信息
    server_tokens off;
    
    # 连接保持设置
    keepalive_timeout 75;	# 略高于默认值,适应API请求
    keepalive_requests 1000;  # 单个连接的最大请求数
    
    # 添加 MIME 类型映射(仅添加mime.types中没有的类型)
    types {
        # 确保 .mjs 文件有正确的 MIME 类型(多数mime.types不包含此项)
        application/javascript mjs;
    }

    # 客户端请求限制(防止滥用)
    client_body_buffer_size 128k;
    client_max_body_size 50M;           # 统一调整为50M,匹配大文件上传场景
    client_header_buffer_size 1k;
    large_client_header_buffers 4 8k;

    # 压缩配置(Linux下Gzip效率较高)
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/xml+rss
        application/json
        application/x-font-ttf
        font/opentype
        image/svg+xml;

    # 全局安全头部(生产环境重要防护)
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # 访问日志格式(包含请求时间监控)
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for" '
                    'rt=$request_time uct="$upstream_connect_time" '
                    'uht="$upstream_header_time" urt="$upstream_response_time"';
    
    # Linux标准日志路径(需确保nginx用户有写入权限)
    access_log /var/log/nginx/access.log main buffer=32k flush=5s;
    
    # Linux临时文件路径(标准位置)
    client_body_temp_path /var/lib/nginx/client_body;
    proxy_temp_path /var/lib/nginx/proxy;
    fastcgi_temp_path /var/lib/nginx/fastcgi;
    uwsgi_temp_path /var/lib/nginx/uwsgi;
    scgi_temp_path /var/lib/nginx/scgi;

    # 文件描述符缓存(Linux下显著提升静态文件性能)
    open_file_cache max=2000 inactive=20s;
    open_file_cache_valid 60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # 限流区域定义(防DDoS/防刷基础:10MB内存,约16万IP,每秒10个请求)
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
    
    # 限制特定IP的并发连接数(可选,防DDoS基础)
    limit_conn_zone $binary_remote_addr zone=addr:5m;
    
    # 上游服务器定义(便于后续扩展为集群)
    upstream backend {
        server 127.0.0.1:8085;
        # Linux下保持连接池,减少TCP握手开销
        keepalive 32;
    }

    server {
        listen 8025;
        server_name localhost;

        # 全局默认字符集
        charset utf-8;

        # 自定义错误页面(提升用户体验)
        error_page 400 401 402 403 404 /error.html;
        error_page 500 502 503 504 /50x.html;

        # 根路径处理
        location / {
            root /usr/share/nginx/html;  # Linux常见默认路径
            index index.html index.htm;

            # 单页应用路由支持(处理点击页面刷新,提示404的问题)
            try_files $uri $uri/ /index.html;

            # 禁用缓存
            # 使用 "no-cache, no-store, must-revalidate" 的场景:当内容绝对不允许被任何中间环节存储或提供旧版本时使用。适用于包含敏感信息的页面或应用入口文件。
            add_header Cache-Control "no-cache, no-store, must-revalidate";
            add_header Pragma "no-cache";
            expires -1;
            
            # 静态资源智能缓存策略:带版本号(哈希或查询参数)的资源使用长期缓存,否则使用短期缓存
            location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot|webp|avif)$ {
                # 默认设置:短期缓存(7天),适用于不带版本号的资源
                expires 7d;
                add_header Cache-Control "public, max-age=604800";
                
                # 情况1:文件名包含哈希(如 main.abc123.js) - 使用长期强缓存
                # 修正:正则表达式语法错误,使用正确的匹配语法
                # 匹配8位及以上十六进制哈希值的文件名
                if ($request_uri ~* "\.[a-f0-9]{8,}\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|webp|avif)(\?|$)") {
                    expires 1y;
                    add_header Cache-Control "public, max-age=31536000, immutable" always;
                }
                
                # 情况2:URL带版本查询参数(如 main.js?v=1.2.3) - 使用长期缓存
                if ($args ~* "^v=|version=|ver=|t=|ts=") {
                    expires 1y;
                    add_header Cache-Control "public, max-age=31536000, immutable" always;
                }
                
                # 关闭访问日志,减少磁盘IO
                access_log off;
                log_not_found off;
                
                # 静态资源安全头
                add_header X-Content-Type-Options "nosniff" always;
            }
            
            # 单独处理HTML文件,确保不缓存
            location = /index.html {
                expires -1;
                add_header Cache-Control "no-cache, no-store, must-revalidate";
                add_header Pragma "no-cache";

                # 首页额外安全头
                add_header X-Frame-Options "DENY" always;
            }
        }

        # 代理设置
        # 处理跨域问题,Nginx 用的是 8025 端口,Tomcat 用的是 8080 端口,这就存在跨域的情况
        # 前端请求:http://localhost:8025/api/users
        # Nginx 转发:http://localhost:8080/users
        location /api/ {
            # 使用upstream定义的后端服务器组
            proxy_pass http://backend/;
            
            # HTTP 1.1 连接复用(Linux下效果显著)
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            
            # 设置用户客户端的请求头
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Port $server_port;
            # 传递客户端原始Host(某些后端需要)
            proxy_set_header X-Original-Host $http_host;

            # 设置请求体大小限制
            client_max_body_size 50M;  # 与全局设置保持一致
            client_body_buffer_size 256k;  # 大文件上传优化

            # 代理缓冲区优化(Linux下可适当增大)
            proxy_buffering on;
            proxy_buffer_size 8k;
            proxy_buffers 16 8k;
            proxy_busy_buffers_size 16k;
            
            # 超时设置(大文件上传需要更长时间)
            proxy_connect_timeout 90s;    # 连接后端服务器的超时时间
            proxy_send_timeout 300s;      # 向后端发送请求的超时时间
            proxy_read_timeout 300s;      # 从后端读取响应的超时时间

            # 重试机制(后端故障时)
            proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
            proxy_next_upstream_tries 2;

            # 传输设置
            proxy_request_buffering on;         # 生产环境建议开启,避免内存压力
            proxy_max_temp_file_size 1024m;     # 允许较大的临时文件
            
            # 处理OPTIONS预检请求(跨域必要配置)
            if ($request_method = 'OPTIONS') {
                add_header Access-Control-Allow-Origin $http_origin;
                add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
                add_header Access-Control-Allow-Headers "Authorization, Content-Type, X-Requested-With";
                add_header Access-Control-Max-Age 86400;
                add_header Content-Type 'text/plain charset=UTF-8';
                add_header Content-Length 0;
                return 204;
            }
            
            # 添加CORS头
            add_header Access-Control-Allow-Origin $http_origin always;
            add_header Access-Control-Allow-Credentials true always;
            add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
            add_header Access-Control-Allow-Headers "Authorization, Content-Type, X-Requested-With" always;

            # 代理接口安全头
            add_header X-Content-Type-Options "nosniff" always;
            
            # 基础限流保护(防止API滥用)
            limit_req zone=api_limit burst=10 nodelay;
            limit_req_status 429;
        }

        # WebSocket代理
        location /ws/ {
            # 保留 /ws/ 路径
            proxy_pass http://backend/ws/;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;

            # 移除Origin头,让后端认为是同源请求
            proxy_set_header Origin "";

            # 设置用户客户端的请求头
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Port $server_port;

            # 超时设置
            proxy_connect_timeout 60s;    # 连接后端服务器的超时时间
            proxy_read_timeout 3600s;     # WebSocket连接需要更长的超时时间
            proxy_send_timeout 60s;       # 向后端发送请求的超时时间

            # 禁用缓存和缓冲
            proxy_buffering off;
            proxy_request_buffering off;

            # WebSocket限流(比API宽松)
            limit_req zone=api_limit burst=30 nodelay;
        }

        # 专门处理 PDF Worker 文件
        location = /pdf.worker.min.mjs {
            # 1. 设置正确的MIME类型(可选:上面已经通过types增加了)
            # add_header Content-Type application/javascript;

            # 2. 核心:对带查询参数的请求设置长期强缓存
            if ($args ~* "v=") {
                # 当URL中包含版本参数(如 ?v=2025.12.02-rev1)时,启用1年缓存
                expires 1y;
                add_header Cache-Control "public, max-age=31536000, immutable" always;
            }

            # 3. 安全兜底:对于不带版本号的请求,可设置较短缓存或不缓存
            if ($args = "") {
                expires -1;
                # 使用 "no-cache" 的场景:当你希望兼顾性能与新鲜度,允许缓存但强制验证时使用,适用于静态资源但需要及时更新的情况
                add_header Cache-Control "no-cache" always;
            }

            # 4. 确保文件存在,如果文件不存在,不重定向到 index.htm
            try_files $uri =404;
            
            # 5. 添加安全头
            add_header X-Content-Type-Options "nosniff" always;
        }

        # 错误页面处理
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/share/nginx/html;  # Linux常见默认路径
            internal;  # 标记为内部location,禁止外部直接访问
        }
        
        # 健康检查端点(生产环境监控用)
        location /health {
            access_log off;
            # 返回包含时间戳的健康状态
            return 200 "{\"status\":\"healthy\",\"timestamp\":\"$time_local\",\"service\":\"nginx\"}\n";
            add_header Content-Type application/json always;
            add_header Cache-Control "no-store" always;
        }
        
        # 敏感文件保护
        location ~ /\.(ht|git|svn|env|dockerignore|ini|conf|cfg|bak|old|swp)$ {
            deny all;
            access_log off;
            log_not_found off;
            return 404;
        }
        
        # Nginx状态监控(调试用,生产环境需加认证)
        location /nginx_status {
            stub_status on;
            access_log off;
            # 生产环境建议限制访问IP
            allow 127.0.0.1;
            allow 192.168.0.0/16;  # 示例:内网网段
            deny all;
            # 生产环境强烈建议添加HTTP基础认证
            # auth_basic "Nginx Status";
            # auth_basic_user_file /etc/nginx/htpasswd;
        }
        
        # 限制请求频率(防刷/防DDoS基础配置)
        location ~ ^/(api|ws)/ {
            limit_req zone=api burst=20 nodelay;
            limit_req_status 429;
        }
    }
    
    # 定义限流区域(防刷配置)
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
}

Windows

# Windows生产环境配置
# Windows下I/O模型限制,多进程效果有限,建议保持1个
worker_processes 1;

# 指定pid文件路径(Windows环境明确路径)
pid logs/nginx.pid;

events {
    # Windows下单个进程连接数建议值,可依据实际负载微调
    worker_connections 1024;
    
    # Windows下使用性能较好的事件模型(Windows特定优化)
    use select;  # Windows默认,也可尝试使用'poll'或'iocp'(如支持)
    
    # 优化连接接受(Windows下可能效果有限,但建议保留)
    multi_accept on;
}

http {
    include mime.types;
    default_type application/octet-stream;
    
    # 基础性能优化
    sendfile on;
    sendfile_max_chunk 512k;    # 限制每次sendfile调用大小,避免阻塞
    tcp_nodelay on;             # 禁用Nagle算法,提升小包响应速度
    
    # 连接保持设置
    keepalive_timeout 75;       # 略高于默认值,适应API请求
    keepalive_requests 1000;    # 单个长连接最大请求数
    
    # 安全:隐藏Nginx版本信息(生产环境必备)
    server_tokens off;

    # 添加 MIME 类型映射(仅添加mime.types中没有的类型)
    types {
        # 确保 .mjs 文件有正确的 MIME 类型(多数mime.types不包含此项)
        application/javascript mjs;
    }

    # 客户端请求限制(防止滥用)
    client_body_buffer_size 128k;
    client_max_body_size 50M;           # 统一调整为50M,匹配大文件上传场景
    client_header_buffer_size 2k;
    large_client_header_buffers 4 8k;
    
    # 请求超时设置
    client_body_timeout 60s;
    client_header_timeout 60s;
    send_timeout 180s;

    # 启用Gzip压缩(显著减少文本传输大小,提升性能)
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 6;                  # 平衡压缩率与CPU消耗
    gzip_proxied any;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/xml+rss
        application/json
        application/x-font-ttf
        font/opentype
        image/svg+xml;
    # 压缩分片长度,避免处理大文件时占用过多内存
    gzip_buffers 16 8k;
    
    # 全局安全头部(生产环境重要防护)
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    # 注意:CSP(Content-Security-Policy)需根据实际资源调整,此处未添加
    
    # 访问日志格式(包含响应时间,便于性能分析)
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for" '
                    'rt=$request_time';
    
    access_log logs/access.log main buffer=128k flush=10s;
    error_log logs/error.log warn;
    
    # Windows临时文件路径(避免C盘系统目录,确保目录存在)
    client_body_temp_path temp/client_body_temp;
    proxy_temp_path temp/proxy_temp;
    fastcgi_temp_path temp/fastcgi_temp;
    
    # 文件缓存(Windows下对静态文件服务有帮助)
    open_file_cache max=2000 inactive=30s;
    open_file_cache_valid 60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors off;  # Windows下可关闭避免日志噪声

    # 限流区域定义(防DDoS/防刷基础:10MB内存,约16万IP,每秒10个请求)
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
    
    # 限制特定IP的并发连接数(可选,防DDoS基础)
    limit_conn_zone $binary_remote_addr zone=addr:5m;

    server {
        listen 8025;
        # 考虑未来支持HTTPS的配置预留(需获取SSL证书)
        # listen 443 ssl;
        # ssl_certificate cert/server.crt;
        # ssl_certificate_key cert/server.key;
        # ssl_protocols TLSv1.2 TLSv1.3;
        # ssl_ciphers HIGH:!aNULL:!MD5;

        server_name localhost;
        
        # 全局默认字符集
        charset utf-8;
        
        # 自定义错误页面(提升用户体验)
        error_page 400 401 402 403 404 /error.html;
        error_page 500 502 503 504 /50x.html;

        # 根路径处理
        location / {
            root html;
            index index.html index.htm;

            # 单页应用路由支持(处理点击页面刷新,提示404的问题)
            try_files $uri $uri/ /index.html;

            # 禁用缓存
            # 使用 "no-cache, no-store, must-revalidate" 的场景:当内容绝对不允许被任何中间环节存储或提供旧版本时使用。适用于包含敏感信息的页面或应用入口文件。
            add_header Cache-Control "no-cache, no-store, must-revalidate";
            add_header Pragma "no-cache";
            expires -1;
            
            # 静态资源智能缓存策略:带版本号(哈希或查询参数)的资源使用长期缓存,否则使用短期缓存
            location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot|webp|avif)$ {
                # 默认设置:短期缓存(7天),适用于不带版本号的资源
                expires 7d;
                add_header Cache-Control "public, max-age=604800";
                
                # 情况1:文件名包含哈希(如 main.abc123.js) - 使用长期强缓存
                # 修正:正则表达式语法错误,使用正确的匹配语法
                # 匹配8位及以上十六进制哈希值的文件名
                if ($request_uri ~* "\.[a-f0-9]{8,}\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|webp|avif)(\?|$)") {
                    expires 1y;
                    add_header Cache-Control "public, max-age=31536000, immutable" always;
                }
                
                # 情况2:URL带版本查询参数(如 main.js?v=1.2.3) - 使用长期缓存
                if ($args ~* "^v=|version=|ver=|t=|ts=") {
                    expires 1y;
                    add_header Cache-Control "public, max-age=31536000, immutable" always;
                }
                
                # 关闭访问日志,减少磁盘IO
                access_log off;
                log_not_found off;
                
                # 静态资源安全头
                add_header X-Content-Type-Options "nosniff" always;
            }
            
            # 单独处理HTML文件,确保不缓存
            location = /index.html {
                expires -1;
                add_header Cache-Control "no-cache, no-store, must-revalidate";
                add_header Pragma "no-cache";
                
                # 首页额外安全头
                add_header X-Frame-Options "DENY" always;
            }
        }

        # 代理设置
        # 处理跨域问题,Nginx 用的是 8025 端口,后端用的是 8085 端口,这就存在跨域的情况
        # 前端请求:http://localhost:8025/api/users
        # Nginx 转发:http://localhost:8085/users
        location /api/ {
            # Windows环境下使用127.0.0.1可能比localhost更稳定
            proxy_pass http://127.0.0.1:8085/;
            
            # HTTP/1.1 连接复用
            proxy_http_version 1.1;
            proxy_set_header Connection "";

            # 设置用户客户端的请求头
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            # Windows环境下添加额外的代理头
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Port $server_port;
            # 传递客户端原始Host(某些后端需要)
            proxy_set_header X-Original-Host $http_host;

            # 设置请求体大小限制
            client_max_body_size 50M;  # 与全局设置保持一致
            client_body_buffer_size 256k;  # 大文件上传优化

            # 代理缓冲区优化(Windows下需谨慎设置)
            proxy_buffering on;
            proxy_buffer_size 8k;
            proxy_buffers 16 8k;
            proxy_busy_buffers_size 16k;
            proxy_temp_file_write_size 64k;
            
            # 超时设置(大文件上传需要更长时间)
            proxy_connect_timeout 90s;    # 连接后端服务器的超时时间
            proxy_send_timeout 300s;      # 向后端发送请求的超时时间
            proxy_read_timeout 300s;      # 从后端读取响应的超时时间
            
            # 重试机制(后端故障时)
            proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
            proxy_next_upstream_tries 2;

            # 传输设置
            proxy_request_buffering on;   # 生产环境建议开启,避免内存压力
            proxy_max_temp_file_size 1024m;  # 允许较大的临时文件
            
            # 处理OPTIONS预检请(跨域必要配置)
            if ($request_method = 'OPTIONS') {
                add_header Access-Control-Allow-Origin $http_origin;
                add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS, PATCH";
                add_header Access-Control-Allow-Headers "Authorization, Content-Type, X-Requested-With, X-CSRF-Token, Accept";
                add_header Access-Control-Allow-Credentials true;
                add_header Access-Control-Max-Age 86400;
                add_header Content-Type 'text/plain charset=UTF-8';
                add_header Content-Length 0;
                return 204;
            }
            
            # 添加CORS头
            add_header Access-Control-Allow-Origin $http_origin always;
            add_header Access-Control-Allow-Credentials true always;
            add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS, PATCH" always;
            add_header Access-Control-Allow-Headers "Authorization, Content-Type, X-Requested-With, X-CSRF-Token, Accept" always;
            
            # 代理接口安全头
            add_header X-Content-Type-Options "nosniff" always;
            
            # 基础限流保护(防止API滥用)
            limit_req zone=api_limit burst=10 nodelay;
            limit_req_status 429;
        }

        # WebSocket代理
        location /ws/ {
            # 保留 /ws/ 路径
            # Windows环境下使用127.0.0.1可能比localhost更稳定
            proxy_pass http://127.0.0.1:8085/ws/;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;

            # 移除Origin头,让后端认为是同源请求
            proxy_set_header Origin "";

            # 设置用户客户端的请求头
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Port $server_port;

            # WebSocket超时设置(需要比普通HTTP长)
            proxy_connect_timeout 60s;    # 连接后端服务器的超时时间
            proxy_read_timeout 3600s;     # WebSocket连接需要更长的超时时间
            proxy_send_timeout 3600s;     # 向后端发送请求的超时时间

            # 禁用缓存和缓冲
            proxy_buffering off;
            proxy_request_buffering off;
            
            # WebSocket特定头部
            add_header X-WebSocket-Protocol $http_sec_websocket_protocol always;
            
            # WebSocket限流(比API宽松)
            limit_req zone=api_limit burst=30 nodelay;
        }

        # 专门处理 PDF Worker 文件
        location = /pdf.worker.min.mjs {
            # 1. 设置正确的MIME类型(可选:上面已经通过types增加了)
            # add_header Content-Type application/javascript;

            # 2. 核心:对带查询参数的请求设置长期强缓存
            if ($args ~* "v=") {
                # 当URL中包含版本参数(如 ?v=2025.12.02-rev1)时,启用1年缓存
                expires 1y;
                add_header Cache-Control "public, max-age=31536000, immutable" always;
            }

            # 3. 安全兜底:对于不带版本号的请求,可设置较短缓存或不缓存
            if ($args = "") {
                expires 7d;  # 调整为7天短期缓存,而非完全不缓存
                # 使用 "no-cache" 的场景:当你希望兼顾性能与新鲜度,允许缓存但强制验证时使用,适用于静态资源但需要及时更新的情况
                add_header Cache-Control "public, max-age=604800, must-revalidate" always;
            }

            # 4. 确保文件存在,如果文件不存在,不重定向到 index.htm
            try_files $uri =404;
            
            # 5. Windows环境下添加安全头
            add_header X-Content-Type-Options "nosniff" always;
        }

        # 错误页面处理
        location = /50x.html {
            root html;
            internal;  # 防止直接访问
        }
        
        location = /error.html {
            root html;
            internal;  # 防止直接访问
        }
        
        # 健康检查端点(生产环境监控用)
        location /health {
            access_log off;
            # 返回包含时间戳的健康状态
            return 200 "{\"status\":\"healthy\",\"timestamp\":\"$time_local\",\"service\":\"nginx\"}\n";
            add_header Content-Type application/json always;
            add_header Cache-Control "no-store" always;
        }
        
        # 敏感文件保护
        location ~ /\.(ht|git|svn|env|dockerignore|ini|conf|cfg|bak|old|swp)$ {
            deny all;
            access_log off;
            log_not_found off;
            return 404;
        }
        
        # Nginx状态监控(调试用,生产环境需加认证)
        location /nginx_status {
            stub_status on;
            access_log off;
            # 仅允许本地访问
            allow 127.0.0.1;
            # 生产环境建议添加HTTP基础认证
            # auth_basic "Nginx Status";
            # auth_basic_user_file conf/htpasswd;
            deny all;
        }
        
        # 禁止访问敏感目录
        location ~ ^/(\.git|\.svn|config|logs|temp|backup)/ {
            deny all;
            return 403;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值