Miklix

Match Location Based on File Extension with NGINX

Published: March 5, 2015 at 8:44:46 PM UTC

This article explains how to do pattern matching based on file extensions in location contexts in NGINX, useful for URL rewriting or otherwise handling files differently based on their type.


The information in this post is based on NGINX 1.4.6 running on Ubuntu Server 14.04 x64. It may or may not be valid for other versions.

I’m not all that good at regular expressions (something I should probably work on, I know), so I often need to read up on it when I have to do more than the very simplest of pattern matching in for example NGINX’s location context.

One that is very useful if you need to handle specific file types differently is the ability to match a location based on the extension of the requested file. And it’s very easy too, your location directive could simply look like this:

location ~* \.(js|css|html|txt)$
{
    // do something here
}

Of course, you can just change the extensions to whatever you need.

The above example is case-insensitive (for example, it will match both .js and .JS). If you want it to be case-sensitive, just remove the * after the ~.

What you do with the match is up to you; typically, you’d rewrite it to a back-end that does some sort of preprocessing, or you may just want to read the files from other folders than what it looks like to the public, the possibilities are endless ;-)

Share on BlueskyShare on FacebookShare on LinkedInShare on TumblrShare on XShare on LinkedInPin on Pinterest

Mikkel Bang Christensen

About the Author

Mikkel Bang Christensen
Mikkel is the creator and owner of miklix.com. He has over 20 years experience as a professional computer programmer/software developer and is currently employed full-time for a large European IT corporation. When not blogging, he spends his spare time on a vast array of interests, hobbies, and activities, which may to some extent be reflected in the variety of topics covered on this website.