rewrite rule on location in nginx

Christian asked:

When I write the location in, it works, when I use the same location as a rewrite rule, it doesnt!!! I dont understand the logic. Can someone please explain?

   location /v3/ {
            alias /var/www/api/v3/html/;
            echo $document_uri;
            echo $document_root;
            echo $request_filename;
            echo $request_uri;
            echo $fastcgi_script_name;
   }

When I do the above, I get

/v3/info.php
/var/www/api/v3/html/
/var/www/api/v3/html/info.php
/v3/info.php
/v3/info.php

But if I now change the location to use rewrite:

   location ~ ^/(vd+)/ {
            alias /var/www/api/$1/html/;
            echo $document_uri;
            echo $document_root;
            echo $request_filename;
            echo $request_uri;
            echo $fastcgi_script_name;
   }

The paths all get screwed:

/v3/info.php
/var/www/api/v3/html/
/var/www/api/v3/html/
/v3/info.php
/v3/info.php

How come??

My answer:


You will need to match on the entire URL to do this.

For instance:

location ~ ^/(vd+)/(.*) {
    alias /var/www/api/$1/html/$2;

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.