nginx配置优化建议.md 12 KB

Nginx配置优化建议

✅ 当前配置分析

已正确配置的部分

  1. ✅ HTTPS配置:443端口,SSL证书配置正确
  2. ✅ API代理:/api/ → 后端8766端口
  3. ✅ WebSocket代理:/ws → 后端8766端口
  4. ✅ 前端路由处理:try_files $uri $uri/ /index.html; 正确
  5. ✅ 静态资源缓存:配置合理
  6. ✅ 安全头设置:XSS保护、内容类型检查等

需要修复的问题

  1. ❌ 缺少HTTP到HTTPS重定向

    • 当前HTTP(80端口)和HTTPS(443端口)配置相同
    • 应该将HTTP请求重定向到HTTPS
  2. ❌ 缺少非www到www的重定向

    • 当前只配置了 www.chengyantek.cn
    • 如果用户访问 chengyantek.cn(没有www),没有处理
    • 可能导致URL不一致问题
  3. ⚠️ server_name只有www域名

    • 如果访问非www域名,可能返回默认页面或404

🔧 修复建议

修复1:HTTP重定向到HTTPS

当前问题:

  • HTTP(80端口)和HTTPS(443端口)配置相同
  • 用户访问 http://www.chengyantek.cn 不会自动跳转到HTTPS

修复方法: 将HTTP server块改为重定向:

# HTTP 端口 80 配置(重定向到HTTPS)
server {
    listen       80;
    server_name  www.chengyantek.cn chengyantek.cn;
    
    # 重定向所有HTTP请求到HTTPS
    return 301 https://www.chengyantek.cn$request_uri;
}

修复2:非www重定向到www

当前问题:

  • 只配置了 www.chengyantek.cn
  • 如果用户访问 https://chengyantek.cn,没有server块处理

修复方法: 添加非www域名的HTTPS server块:

# 非www域名重定向到www(HTTPS)
server {
    listen       443 ssl;
    server_name  chengyantek.cn;

    # SSL证书配置(与非www域名相同)
    ssl_certificate "/root/.acme.sh/chengyantek.cn_ecc/fullchain.cer";
    ssl_certificate_key "/root/.acme.sh/chengyantek.cn_ecc/chengyantek.cn.key";

    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1h;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # 重定向到www域名
    return 301 https://www.chengyantek.cn$request_uri;
}

📋 完整优化后的配置

user root;

worker_processes auto;
events {
    worker_connections 8192;
    use epoll;
    multi_accept on;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    # 启用gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/js
        text/xml
        text/javascript
        application/javascript
        application/xml+rss
        application/json;

    # ==================== HTTP 端口 80 配置(重定向到HTTPS)====================
    server {
        listen       80;
        listen       [::]:80;
        server_name  www.chengyantek.cn chengyantek.cn;
        
        # 🔥 重定向所有HTTP请求到HTTPS
        return 301 https://www.chengyantek.cn$request_uri;
    }

    # ==================== HTTPS 端口 443 配置(主要配置)====================
    server {
        listen       443 ssl;
        listen       [::]:443 ssl;
        server_name  www.chengyantek.cn;

        # SSL证书配置
        ssl_certificate "/root/.acme.sh/chengyantek.cn_ecc/fullchain.cer";
        ssl_certificate_key "/root/.acme.sh/chengyantek.cn_ecc/chengyantek.cn.key";

        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 1h;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;

        # 处理favicon.ico请求
        location = /favicon.ico {
            root /root/Lyrria/frontend/dist;
            access_log off;
            log_not_found off;
            expires 1y;
            add_header Cache-Control "public, immutable";
        }

        # 处理robots.txt请求
        location = /robots.txt {
            access_log off;
            log_not_found off;
            return 200 "User-agent: *\nDisallow:\n";
        }

        # WebSocket连接代理
        location /ws {
            proxy_pass http://127.0.0.1:8766;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            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_read_timeout 3600s;
            proxy_send_timeout 3600s;
            proxy_connect_timeout 10s;
        }

        # API接口代理
        location ^~ /api/ {
            proxy_pass http://127.0.0.1:8766$request_uri;
            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_read_timeout 60s;
            proxy_send_timeout 60s;
            proxy_connect_timeout 10s;
        }

        # 客户端指标上报接口代理
        location = /metrics/client {
            proxy_pass http://127.0.0.1:8766/metrics/client;
            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_read_timeout 60s;
            proxy_send_timeout 60s;
            proxy_connect_timeout 10s;
        }

        # 静态资源缓存配置
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
            if ($request_method = 'OPTIONS') {
                add_header Access-Control-Allow-Origin '*' always;
                add_header Access-Control-Allow-Methods 'GET, OPTIONS' always;
                add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
                add_header Access-Control-Max-Age 1728000 always;
                add_header Content-Type 'text/plain; charset=utf-8' always;
                add_header Content-Length 0 always;
                return 204;
            }

            root /root/Lyrria/frontend/dist;
            expires 1y;
            add_header Cache-Control "public, immutable" always;
            add_header X-Content-Type-Options nosniff always;
            add_header Access-Control-Allow-Origin '*' always;
            add_header Access-Control-Allow-Methods 'GET, OPTIONS' always;
        }

        # 前端静态文件服务
        location / {
            if ($request_method = 'OPTIONS') {
                add_header Access-Control-Allow-Origin '*' always;
                add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
                add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
                add_header Access-Control-Max-Age 1728000 always;
                add_header Content-Type 'text/plain; charset=utf-8' always;
                add_header Content-Length 0 always;
                return 204;
            }

            root /root/Lyrria/frontend/dist;
            try_files $uri $uri/ /index.html;
            
            # 安全头设置
            add_header X-Frame-Options "SAMEORIGIN" always;
            add_header X-Content-Type-Options "nosniff" always;
            add_header X-XSS-Protection "1; mode=block" always;
            add_header Referrer-Policy "strict-origin-when-cross-origin" always;
            # CORS 响应头
            add_header Access-Control-Allow-Origin '*' always;
            add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
            add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
            
            # HTML文件不缓存
            location ~* \.html$ {
                add_header Cache-Control "no-cache, no-store, must-revalidate";
                add_header Pragma "no-cache";
                add_header Expires "0";
            }
        }
    }

    # ==================== 非www域名重定向到www(HTTPS)====================
    server {
        listen       443 ssl;
        listen       [::]:443 ssl;
        server_name  chengyantek.cn;

        # SSL证书配置
        ssl_certificate "/root/.acme.sh/chengyantek.cn_ecc/fullchain.cer";
        ssl_certificate_key "/root/.acme.sh/chengyantek.cn_ecc/chengyantek.cn.key";

        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 1h;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;

        # 🔥 重定向到www域名
        return 301 https://www.chengyantek.cn$request_uri;
    }
}

🚀 修复步骤

步骤1:备份当前配置

cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

步骤2:修改HTTP server块

将HTTP server块改为重定向:

# HTTP 端口 80 配置(重定向到HTTPS)
server {
    listen       80;
    listen       [::]:80;
    server_name  www.chengyantek.cn chengyantek.cn;
    
    # 重定向所有HTTP请求到HTTPS
    return 301 https://www.chengyantek.cn$request_uri;
}

步骤3:添加非www重定向server块

在HTTPS server块后面添加:

# 非www域名重定向到www(HTTPS)
server {
    listen       443 ssl;
    listen       [::]:443 ssl;
    server_name  chengyantek.cn;

    # SSL证书配置
    ssl_certificate "/root/.acme.sh/chengyantek.cn_ecc/fullchain.cer";
    ssl_certificate_key "/root/.acme.sh/chengyantek.cn_ecc/chengyantek.cn.key";

    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1h;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # 重定向到www域名
    return 301 https://www.chengyantek.cn$request_uri;
}

步骤4:测试配置

# 测试nginx配置语法
nginx -t

步骤5:重载配置

# 如果测试通过,重载配置
nginx -s reload
# 或
systemctl reload nginx

步骤6:验证重定向

# 测试HTTP到HTTPS重定向
curl -I http://www.chengyantek.cn/share
# 应该返回 301 重定向到 https://www.chengyantek.cn/share

# 测试非www到www重定向
curl -I https://chengyantek.cn/share
# 应该返回 301 重定向到 https://www.chengyantek.cn/share

✅ 修复后的效果

修复前的问题

  1. ❌ 访问 http://www.chengyantek.cn → 不会自动跳转到HTTPS
  2. ❌ 访问 https://chengyantek.cn → 可能返回404或默认页面
  3. ❌ URL不一致,可能导致微信JSSDK签名错误

修复后的效果

  1. ✅ 访问 http://www.chengyantek.cn → 自动重定向到 https://www.chengyantek.cn
  2. ✅ 访问 http://chengyantek.cn → 自动重定向到 https://www.chengyantek.cn
  3. ✅ 访问 https://chengyantek.cn → 自动重定向到 https://www.chengyantek.cn
  4. ✅ 所有访问统一使用 https://www.chengyantek.cn
  5. ✅ URL一致,微信JSSDK签名正确

📋 关键修改点总结

修改1:HTTP重定向到HTTPS

server {
    listen 80;
    server_name www.chengyantek.cn chengyantek.cn;
    return 301 https://www.chengyantek.cn$request_uri;  # 添加重定向
}

修改2:非www重定向到www

server {
    listen 443 ssl;
    server_name chengyantek.cn;
    # ... SSL配置 ...
    return 301 https://www.chengyantek.cn$request_uri;  # 添加重定向
}

⚠️ 重要提示

  1. SSL证书路径:确保非www重定向server块中的证书路径正确
  2. 测试配置:修改后务必运行 nginx -t 测试
  3. 重载配置:测试通过后再重载,避免服务中断
  4. 验证重定向:修改后测试各种URL访问,确保重定向正常

✅ 总结

当前配置的优点:

  • ✅ HTTPS配置正确
  • ✅ API和WebSocket代理正确
  • ✅ 前端路由处理正确

需要修复的问题:

  • ❌ 缺少HTTP到HTTPS重定向
  • ❌ 缺少非www到www重定向

修复后:

  • ✅ 所有访问统一使用 https://www.chengyantek.cn
  • ✅ URL一致,解决微信JSSDK URL不匹配问题
  • ✅ 更好的SEO和用户体验

修复后,微信JSSDK的URL不匹配问题应该会解决!