NGINX重定向后example.com缓存失效及内容更新异常求助
解决方案
一、解决example.com重定向缓存问题
浏览器会长期缓存301永久重定向响应,这是导致普通窗口无法正常重定向的核心原因。可以通过以下两种方式处理:
临时改用302临时重定向(快速生效)
修改HTTP和HTTPS的example.com重定向配置,添加缓存控制头禁止缓存重定向响应,同时改用302临时重定向:
# HTTP 重定向块 server { listen 80; server_name example.com www.example.com; # 禁止浏览器缓存重定向响应 add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0"; add_header Pragma "no-cache"; add_header Expires "Thu, 01 Jan 1970 00:00:00 GMT"; # 临时用302,等用户旧缓存过期后改回301 return 302 https://www.example.com$request_uri; } # HTTPS example.com 重定向块 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; # 禁止浏览器缓存重定向响应 add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0"; add_header Pragma "no-cache"; add_header Expires "Thu, 01 Jan 1970 00:00:00 GMT"; return 302 https://www.example.com$request_uri; }
等1-2周(大部分用户的旧301缓存过期)后,再将302改回301即可。
二、确保用户看到最新内容(解决index.html缓存问题)
React构建的静态资源(js/css等)带有哈希值,可安全长缓存,但入口文件index.html无哈希,必须禁止缓存才能加载最新内容。修改www.example.com的server块配置:
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-store, no-cache, must-revalidate, max-age=0"; add_header Pragma "no-cache"; add_header Expires "Thu, 01 Jan 1970 00:00:00 GMT"; } location / { try_files $uri /index.html; } # 静态资源保持长缓存(已有配置无需修改) location ~* \.(?:ico|css|js|gif|jpe?g|png|woff2?|eot|ttf|otf|svg)$ { expires 6M; access_log off; add_header Cache-Control "public"; } location ~ /\. { deny all; } }
三、验证并重启NGINX
修改配置后先校验语法:
sudo nginx -t
校验通过后重启服务:
sudo systemctl restart nginx
内容的提问来源于stack exchange,提问作者YaShpaL Sunar
相关产品推荐
相关产品推荐

