You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NGINX配置:实现域名重定向并强制浏览器加载最新内容

解决方案

一、修复重定向逻辑,确保统一指向www.example.com

现有HTTP服务块使用$host会导致example.com的HTTP请求先跳转至https://example.com,再二次跳转至www域名,不仅增加跳转次数,还可能让浏览器缓存example.com的HTTPS站点记录。修改为直接跳转至www的HTTPS地址:

server {
    listen 80;
    server_name example.com www.example.com;
    # 直接将所有HTTP请求重定向到HTTPS的www域名,避免中间跳转
    return 301 https://www.example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    # 非www的HTTPS请求直接重定向到www
    return 301 https://www.example.com$request_uri;
}

二、优化缓存策略,确保用户获取最新内容

React构建的静态资源(JS/CSS等)文件名自带哈希值(如main.abc123.js),这类文件可安全设置长缓存;但入口文件index.html必须禁止缓存,否则用户会加载旧版本页面。修改www站点的配置:

server {
    listen 443 ssl;
    server_name www.example.com;

    ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    root /var/www/html;
    index index.html;

    # 强制浏览器每次请求都拉取最新的index.html
    location = /index.html {
        add_header Cache-Control "no-cache, no-store, must-revalidate";
        expires 0;
        add_header Pragma "no-cache";
    }

    location / {
        try_files $uri /index.html;
    }

    # 静态资源带哈希,设置永久缓存(文件名变化即触发更新)
    location ~* \.(?:ico|css|js|gif|jpe?g|png|woff2?|eot|ttf|otf|svg)$ {
        expires 1y;
        access_log off;
        add_header Cache-Control "public, immutable";
    }

    location ~ /\. {
        deny all;
    }
}

三、处理已存在的浏览器缓存

针对已缓存旧重定向或旧页面的用户,可临时采取以下操作:

  • 指导用户使用Ctrl+Shift+R强制刷新页面,清除本地缓存
  • 后续部署新版本时,React的构建哈希会自动更新静态资源文件名,用户加载新的index.html后会自动获取最新资源

内容的提问来源于stack exchange,提问作者khem K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 04:47:11