【问题标题】:Adding caching for specific static files in a reverse proxy in Nginx?在 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;
    }
}
}}

【问题讨论】:

    标签: nginx caching single-page-application


    【解决方案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;
         }
    

    【讨论】:

    • 工作,谢谢!目前无法投票,因为没有足够的声誉。
    猜你喜欢
    • 2017-09-09
    • 2014-04-30
    • 2016-04-04
    • 2016-08-19
    • 2012-11-16
    • 2019-04-17
    • 2023-04-09
    • 2012-09-08
    • 2016-06-04
    相关资源
    最近更新 更多