IIS to nginx migration: `unexpected "{"` erron on \d{^anum^,^anum^} entries to map file

Viewed 277

I was tasked to migrate a php application running in azure/iis into nginx+fpm combo over a GNU+Linux machine.

The web.config contains:

<rule name="Some match">
<match url=".*"/>
<conditions>
 <add input="{URL}" pattern="^power_ranger/(\d{4,9})$" />
</conditions>
<action type="Rewrite" url="/power_ranger.php?ranger={C:1}"/>
</rule>

Afterwards follow the instruction seen in https://serverfault.com/questions/441235/maintaining-redirects-in-nginx-from-an-external-source#441517 I created the following map file named rewrites.map:

^power_ranger/(\d{4,9})$  /power_ranger.php?ranger=$2

And on the vhost configuration I put the following:

map $uri $new {
       include /home/user/powerangerApp/rewrites.map;
}

if ($new) {
       rewrite ^ $new redirect;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /home/user/powerangerApp;
    index index.php;

    server_name _;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
}

Then when I try to reload the nginx I get the following error:

nginx: [emerg] unexpected "{" in /home/user/powerangerApp/rewrites.map:1

So in my guess is that the nginx cannot map pcre regex. So how can I make nginx to do that?

Edit 1:

As seen in https://serverfault.com/questions/482372/nginx-httpmapmodule-regex-variables#482391:

I tried to change the regex with:

?P^power_ranger/(\d{4,9})$  /power_ranger.php?ranger=$2

And still got the same error.

Edit 2

So far I figured out that I need an if condition to my nginx configuration:

 if ( $url ~* "^power_ranger/(\d{4,9})$"){
   rewrite ^ /power_ranger.php?ranger=$2
 }

But I get an error:

unknown directive ranger=$2 in /etc/nginx/nginx.conf:^some_number^

Do you fellows knwo how to fix that?

1 Answers

The regex should be changed into:

~\/power_ranger\/(\d{4,9})$  /power_ranger.php?ranger=$1;

As you can see there are were syntax errors.

Also the nginx.conf should be:

map $uri $new {
       include /home/user/powerangerApp/rewrites.map;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /home/user/powerangerApp;
    index index.php;

    server_name _;

    location / {
        # On way too many rewrite rules you may avoit the line above
        try_files $uri $uri/ =404; 

        if ($new) {
          rewrite ^ $new redirect redirect;
        }
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
}

Please keep in mind that the redirect on rewrite may proven to be savior in order to get the job done.

Related