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:
{
// 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 ;-)