Search code examples
nginxnginx-locationnginx-config

nginx regex engine on URL rewrite doesn't support squiggly brackets?


My nginx config seems to fail on the syntax check if I try to use the squiggly brackets, even though this answer implies that nginx uses PECR, and this fiddle shows that the squiggly brackets work under PECR (although it does say PECR PHP in brackets...).

So, if I put this under my server > location block:

location / {
    rewrite ^/([0-9]{4})$ /page.php;
}

I get the following error from nginx's syntax checker:

nginx: [emerg] directive "rewrite" is not terminated by ";" in /etc/nginx/sites-enabled/default:37

nginx: configuration file /etc/nginx/nginx.conf test failed

And if I only get rid of the squiggly part, and leave it with this:

location / {
    rewrite ^/([0-9])$ /page.php;
}

Then everything is okay:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

So, what exactly is the fault here, and how can get my URL-rewriter to accept specifically 4 digits in the URL rewrite rule?


Solution

  • From the manual page for rewrite:

    If a regular expression includes the “}” or “;” characters, the whole expressions should be enclosed in single or double quotes.

    The } and ; characters have a special meaning in the Nginx configuration file, so there use within a regular expression needs to be protected by enclosing the expression within quotes.

    Same applies to regular expressions appearing in location, if and map directives (and any others I may have forgotten).

    For example:

    rewrite "^/[0-9]{4}$" /page.php last;