今天老王突然发现之前配置的两个反代网站的样式都出了问题,检查发现 CSS 文件用的还是最早的一版,文件没有更新,自然做的修改也都没有生效。老王就分享下这个问题的原因和解决方法。
一、反代环境
网站是基于 Nginx 配置的反向代理,详细的环境如下:
- 系统:CentOS 7
- Nginx 版本:nginx 1.22
- 网络换境:LNMP,基于宝塔面板
Nginx 反向代理的配置方法是直接用的宝塔自带的功能,配置文件如下:
#PROXY-START/ location ^~ / { proxy_pass http://*.*.*.*/; 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 REMOTE-HOST $remote_addr; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_http_version 1.1; add_header Cache-Control no-cache; # proxy_hide_header Upgrade; add_header X-Cache $upstream_cache_status; #Set Nginx Cache set $static_file191zVG 0; if ( $uri ~* "\.(gif|png|jpg|css|js|woff|woff2)$" ) { set $static_file191zVG 1; expires 1m; } if ( $static_file191zVG = 0 ) { add_header Cache-Control no-cache; } } #PROXY-END/
二、CSS 不更新的原因
老王先在互联网上搜了一些教程,发现这种反代网站文件不更新(包括但不限于 CSS、js、png/jpg/gif 图片等)的原因基本都是因为缓存的问题,包括 Nginx 缓存和浏览器缓存。
老王也把这个问题抛给了 ChatGPT,给出的原因也是 Nginx 缓存导致的:
This could be a caching issue. When you use Nginx as a reverse proxy, it can cache static files like CSS for a certain period of time to improve performance. When you updated the CSS file on Server B, Nginx on Server A may still be serving the old, cached version of the file.
三、CSS 不更新的解决方法
对于这个问题,ChatGPT 给出了 4 个解决方法:
- Clear Nginx cache on Server A: If Nginx has a caching mechanism configured, you need to clear the cache. The method to do this will depend on your specific configuration, but often involves deleting the files in your proxy cache path.
-
Use Cache-Control headers: You could modify your configuration on Server B to add Cache-Control headers to your CSS files. The
no-cache
directive will tell proxies (including Nginx on Server A) to revalidate the file every time before serving it. Here’s an example for an Nginx configuration:
location ~* \.css$ { add_header Cache-Control no-cache; }
-
Version your CSS files: Another common approach is to “version” your static files. This means appending a query string to the end of your CSS file references, e.g.
style.css?v=1.2
. When you update the file, you change the version number. Because the URL is different, Nginx (and the client’s browser) will treat it as a different file and won’t use the cached version. - Browser Cache: It might also be a browser caching issue. Try to hard reload the page in your browser (Ctrl + F5 or Cmd + Shift + R).
老王先尝试清除了浏览器的缓存,发现没有效果,所以问题原因不是浏览器缓存导致的。之后又将域名直接解析到源服务器,发现 CSS 文件是更新后的内容,所以可以定位问题原因是配置 Nginx 反代的这台服务器。
Clear Nginx cache on Server A 和 Use Cache-Control headers 也都试了,第一个方法没找到 Nginx 的缓存文件在哪里,宝塔的默认配置文件里好像没有设置,但是在默认的缓存路径里也没找到;第二个方法试了,没有效果。
最后来到了方法 Version your CSS files,简单来说就是在你引用 CSS 文件的时候给它一个版本号,之后做了修改就改一下版本号,如下:
之后再访问网站,发现 CSS 修改成功生效,至此问题成功解决。
暂无评论内容