Andy
Andy

Reputation: 21

NGINX Cache Busting CSS JS URL Rewrite

I'm new to NGINX and trying to set up a portfolio. I've gotten my site working with the exception of a few errors that I noticed through Google Chrome DevTools.

I notice that javascript files aren't loading and have the incorrect path. For example, it tries to load http://site/assets/js/site.1617886701.js but the actual file is http://site/assets/js/site.js

Likewise with a css file I have: It tries to load http://site/assets/css/templates/home..css (for some reason it adds an extra .?) when it should be loading this file: http://site/assets/css/templates/home.css

This is my NGINX config file:

server {
listen 80;
listen [::]:80;
root /var/www/html/;
index index.php index.html index.htm;
server_name site wwww.site.com;

client_max_body_size 100M;

location / {
    try_files $uri $uri/ /index.php?$uri&$args;    
}


location ~ \.php$ {
 include snippets/fastcgi-php.conf;
 fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
     include /etc/nginx/fastcgi_params;
}
location /assets {
   rewrite uikit.min.(\d+).js uikit.min.js permanent;
   rewrite uikit-icons.min.(\d+).js uikit-icons.min.js permanent;
   rewrite uikit.app.min.(\d+).css uikit.app.min.css permanent;
   try_files $uri =404;
   expires max;
   access_log off;
   add_header Pragma public;
   add_header Cache-Control "public, must-revalidate, proxy-revalidate";
 }
}

From my googling online it says something about cache busting. Some people have suggested matching the file names in the NGINX config file which I'm not sure how to do or to change the paths to match the hexadecimal versions which I also don't know where to begin.

I would really appreciate any help from the pros! Thanks so much

Upvotes: 2

Views: 1041

Answers (1)

Danila Vershinin
Danila Vershinin

Reputation: 9895

For example, it tries to load http://site/assets/js/site.1617886701.js but the actual file is http://site/assets/js/site.js

It is not NGINX, it's your web application, which constructs such cache-busting URLs, which expect extra configuration on the side of NGINX.

The way to deal with it, is a rewrite in NGINX:

rewrite ^(.+)\.(\d+)\.(css|js)$ $1.$3 last;

This will rewrite, e.g. any /some/<foo>.<digits>.js to /some/<foo>.js.

It tries to load http://site/assets/css/templates/home..css

Obviously, a bug in your web application's code. Shouldn't be attempted to be fixed in NGINX.

Upvotes: 2

Related Questions