Quick Tip: nginx Global Rewrite Issue - JS, CSS, & Images Not Found

I spent a couple hours struggling with this due to poor logging, I'm documenting it here for future reference.

Issue:

Using an nginx rewrite directive within a location to rewrite "clean" user friendly URLs into server-processible requests results in .js, .css, and image files to not load or produces a "No such file or directory." error in the site's error log when attempting to load pages within the defined location.

Example:

Client submits:

http://example.com/text/2/true

Server translates for internal processing to:

http://example.com/index.php?text_var=text&number_var=2&bool_var=true

Cause:

The rewrite directive doesn't discriminate and processes the rewrite on requests for .js, .css, and image files just as it does for any other file type.

Solution:

Assuming your .js, .css, and image files are stored in the folders js/, css/, and img/ in the web root respectively, prior to the problematic location add the following location directive:

location ~ .(css|img|js)/(.+)$ {
    try_files $uri $uri/ /$1/$2;
}

This will perform a regex to find all requests that end with a match of the pattern {css or img or js}/{any filename}. It will then rewrite the request substituting $1 with the folder and $2 with the file.

CSS Example:

A request for the stylesheet style.css like this

http://example.com/text/2/true/css/style.css

becomes

http://example.com/css/style.css

JS Example:

A request for the javascript file app.js like this

http://example.com/text/2/true/js/app.js

becomes

http://example.com/js/app.js

Image Example:

A request for the image image.png like this

http://example.com/text/2/true/img/image.png

becomes

http://example.com/img/image.png

External reference for additional information:

nginx docs - nginx Rewrite Module

comments powered by Disqus
© 2017. All rights reserved.
© 2017. All rights reserved.