romeovs
romeovs

Reputation: 5953

nginx: try to serve minified files first

I'm trying to optimize my websites by minifying the css, js, svg and whatnot.

This however meddles with my codebase and I would like to keep the original files around. I've set up git to autmoatically minify any css|js|svg to min.css|min.js|min.svg but I'm not editing every php or html file that links to these files to use the .min. extension.

To mend this, I was thinking that I could set up nginx serve the minified versions of the files automatically when a request for the non-minified files is done using the try_files directives and use the non-minified files as a backup if they don't exist.

This is some pseudo-configuration to elaborate what I mean:

location \.(css|js|svg) {
      try_files $minified_uri $uri;  
}

but I have no clue on how to get the $minified_uri here (e.g. /some/style.min.css is served when /some/style.css is requested).

Also, if you think this approach is really bad, please be free to tell me why and show me some alternatives!

Upvotes: 2

Views: 824

Answers (2)

tiernanx
tiernanx

Reputation: 344

This is fairly easy to accomplish using regex variables:

location ~ ^(.+)\.(css|js|svg)$ {
    try_files $1.min.$2 $uri =404;
}

Upvotes: 2

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42899

I don't guarantee that it would work but I guess you can give it a try

location ~ (?<name>[^/]*)\.(?<extention>css|js|svg) {
    try_files $name.min.$extention $name.$extention;  
}

Upvotes: 0

Related Questions