在 Nginx 的反向代理中为特定静态文件添加缓存?
Posted
技术标签:
【中文标题】在 Nginx 的反向代理中为特定静态文件添加缓存?【英文标题】:Adding caching for specific static files in a reverse proxy in Nginx? 【发布时间】:2021-11-22 16:23:36 【问题描述】:我想在客户端浏览器上使用 nginx 缓存单页应用程序的 js 和 css 文件。当我尝试当前注释掉的块时,指定的文件有 404 响应。尝试将块放入 location /
块中,但发生了同样的错误。有人知道怎么修这个东西吗?帮助表示赞赏。
events
http
gzip on;
gzip_vary on;
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable "MSIE [1-6]\.";
# security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
server
server_name SERVER_NAME www.SERVER_NAME;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# adding this block returns 404 response for the specified formats
# location ~* \.(?:css|js)$
# expires 1d;
# add_header Vary Accept-Encoding;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# add_header Cache-Control private;
#
location /
proxy_pass http://localhost:3000;
proxy_redirect off;
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-Host $server_name;
location /api
proxy_pass http://localhost:5000/api;
proxy_redirect off;
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-Host $server_name;
【问题讨论】:
【参考方案1】:您得到 404,因为您没有提供任何服务,请将 proxy_pass 添加到前端应用程序
location ~* \.(?:css|js)$
expires 1d;
add_header Vary Accept-Encoding;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header Cache-Control private;
proxy_pass http://localhost:3000;
【讨论】:
工作,谢谢!目前无法投票,因为没有足够的声誉。以上是关于在 Nginx 的反向代理中为特定静态文件添加缓存?的主要内容,如果未能解决你的问题,请参考以下文章
Nginx 动静分离反向代理缓存添加隐藏信息多级IP透传等配置