So I've made it a thing to finally learn about regular expressions. Normally when working with regular expressions it is necessary to escape delimiters (like "/") with a "\". But when I'm using regular expressions in Nginx it would seem that "/" is treated literally and not as delimiter.

Nginx uses the PCRE engine for evaluating regular expressions, so it makes no sense to me that you can you just throw in an unescaped delimiter without any consequences.

As an example, the below regular expression allows a single IP address and denies all others:

location ~ /\.serverfault {
    deny all;

But I would think it would need to be like this to work correctly:

location ~ \/\.serverfault {
    deny all;

What am I missing here?


The reason you don't have to escape / is that / is not a delimiter.

It sounds like you are accustomed to writing regular expressions in other applications, where a delimiter is required. For instance, in Perl you might write something like:


The key here is that you chose the delimiter. There is nothing special about /. In fact, you could use just about any character. # is fairly common as well.


If you choose a specific delimiter, and that character appears in the regular expression, you must escape it, or choose a different delimiter.

Because nginx does not need the ability to perform replace operations on regular expression matches, (e.g. s/old/new/) it also does not need to use a delimiter, thus when you specify regular expressions in nginx, no delimiter is used, and (almost) nothing needs to be escaped.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.