10

Nginx uses the PCRE engine for evaluating regular expressions, the documentation state that / delimiter is not used so we don’t have to escape the forward slash / in an URI as we may do in a standard regex. An example of a valid nginx regex is location ~* /myapp/.+\.php$

BUT the following code is escaping the forward slash

location ~ ^\/(?:index|core\/ajax\/update|ocs\/v2|ocm-provider\/.+)\.php(?:$|\/)

What does \/ exactly mean in that context and why is it needed when the documentation says otherwise?

intika
  • 8,448
  • 5
  • 36
  • 55
  • 3
    Right, you don't have to escape it but you are not forbidden to escape it. It's no different than choosing to write `\a\j\a\x` instead of `ajax`. Albeit less readable, it's functionally the same. The syntax is self-explanatory since it translates to "literal forward slash" but the reason for using it could stem from the author's force-of-habit or simply because it makes the regex more portable when copy+pasting. – MonkeyZeus Jan 21 '20 at 14:28
  • @MonkeyZeus Thank you for the clarification, at some point of confusion i thought that it was required in the case of a matching group – intika Jan 21 '20 at 14:46
  • 1
    You're welcome. One of the biggest challenges of reading someone else's regex is to decipher intent. Deciphering syntax functionality is becoming increasingly easier especially with regex visualizers such as https://regex101.com/ – MonkeyZeus Jan 21 '20 at 15:03

1 Answers1

5

While Nginx does not require escaping the forward slash / it does not either deny escaping it like we could escape any other character.

The first purpose of the regex special character \ is meant to escape the next character and thus nginx is just translating/matching \/ to / like it would translate/match \j to literal j (the example have no purpose never the less \j match literal j).

One purpose of escaping forward slashes in the context of nginx could be for code portability.

Note that \ followed by a character have probably a different meaning than just escaping the followed char, a complete list is available here

Source: @monkeyzeus and @richard-smith comments

intika
  • 8,448
  • 5
  • 36
  • 55
  • 3
    That does not work. The `\a` and `\x` have specific meanings in a regular expression. The `\j` and `\/` are both safe though and represent `j` and `/` respectively. – Richard Smith Jan 21 '20 at 15:14
  • @RichardSmith thanks indeed i forget about that... i edited the answer – intika Jan 21 '20 at 15:27