Server Setup

NGINX locations: performance impact and optimizations

by ,


We have by far the largest RPM repository with dynamic stable NGINX modules and VMODs for Varnish 4.1 and 6.0 LTS. If you want to install nginx, Varnish and lots of useful modules for them, this is your one stop repository to get all performance related software.
You have to maintain an active subscription in order to be able to use the repository!

The location directive in NGINX can be considered as a core one as it’s the most crucial to have a functional web server.

Without further ado, let’s review on best performance practices in regards to it.

If you have to use regular expressions

Using regular expression in location directive means evaluating/compiling them at runtime, by default.
However, you can greatly improve performance of matching to those locations, by precompiling those regular expressions on NGINX startup.

The magic directive here is pcre_jit on;. Place it in main context (e.g. atop your nginx.conf file).

From the official documentation:

PCRE JIT can speed up processing of regular expressions significantly.

Avoid using regular expressions if you can

Even though you can greatly improve the performance of locations defined by regular expression, they still result in some performance penalty.

Especially so, if there are many of them because NGINX has to evaluate each of them, sequentially.

location ~ ^/foo/bar/?$ {rewrite ^(.*)$ /foo permanent;}
location ~ ^/lorem/ipsum/?$ {rewrite ^(.*)$ /lorem permanent;}

Having a few rules like this is not a big problem. But if you’re rewriting URL structure for many URLs (think thousands),
the best approach would be using exact matching:

location = /foo/bar/ { return 301 /foo; }
location = /foo/bar { return 301 /foo; }
location = /lorem/ipsum/ { return 301 /lorem; }
location = /lorem/ipsum { return 301 /lorem; }

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.