Home > Software design >  Adding caching for specific static files in a reverse proxy in Nginx?
Adding caching for specific static files in a reverse proxy in Nginx?

Time:10-01

I want to cache the js and css files of a single page app with nginx on the clients browser. When i tried the currently commented out block, the specified files had a 404 response. Tried putting the block inside the location / { block and the same error happened. Anyone know how to fix this? Help appreciated.

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;
    }
}
}}

CodePudding user response:

You get 404 because you are not serving anything add proxy_pass to the front app

     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;
     }
  • Related