13

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 {
    allow 1.2.3.4;
    deny all;
}

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

location ~ \/\.serverfault {
    allow 1.2.3.4;
    deny all;
}

What am I missing here?

Harold Fischer
  • 269
  • 3
  • 8

1 Answers1

14

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:

m/\/.serverfault/

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.

m#/.serverfault#

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.

Michael Hampton
  • 237,123
  • 42
  • 477
  • 940
  • 2
    I got confused because https://regex101.com/ says "/ An unescaped delimiter must be escaped with a backslash (\)" when not escaping slashes in the search term. Any ideads why? – JRA_TLL May 13 '21 at 12:06
  • @JRA_TLL As noted above, nginx does not use a delimiter, so there is nothing to escape. – Michael Hampton May 16 '21 at 12:01