Search code examples
phpmod-rewritenginxlocationwebserver

Nginx RegEx to multiple sites make rewrite or internal redirection cycle


I'm trying to migrate my apps from Apache to Nginx. At the first I have the mod_rewrite module that automatically redirects my apps to index.php page like this way:

http://127.0.0.1/fwsibe/acesso <- URL displayed

http://127.0.0.1/fwsibe/index.php/acesso <- url accessed

So, I'm using try_files with alias in my location to automatically redirect the pages and all works fine, but I it's necessary to set a unique location for each app, using the word "sibe" on a RegEx to catch all sites.

One location for each app works:

location /fwsibe/ {
    alias       /var/www/fwsibe/;
    try_files   $uri $uri/ /fwsibe/index.php;
}
location /sibe/ {
    alias       /var/www/sibe/;
    try_files   $uri $uri/ /sibe/index.php;
}
location /portalsibe/ {
    alias       /var/www/portalsibe/;
    try_files   $uri $uri/ /portalsibe/index.php;
}
location /sibemovel/ {
    alias       /var/www/sibemovel/;
    try_files   $uri $uri/ /sibemovel/index.php;
}

But when I try a unique location with RegEx to all "sibe" apps I have "rewrite or internal redirection cycle while internally" error.

location ~ /([a-z]*sibe[a-z]*)/ {
    set         $subdomain          $1;
    alias       /var/www/$subdomain/;
    try_files   $uri $uri/ /$subdomain/index.php;
}

Solution

  • This is related to the way try_files works — http://nginx.org/r/try_files — the final parameter is simply an internal redirect to the specified URL:

    If none of the files were found, an internal redirect to the uri specified in the last parameter is made.

    Presumably, you expect that your try_files would involve the .php handler, but what happens upon a subsequent location search is that you end up in the very same state that you started from.

    As per http://nginx.org/r/location, the order of the location directives matters — the first regular expression to match wins the case:

    Then regular expressions are checked, in the order of their appearance in the configuration file. The search of regular expressions terminates on the first match, and the corresponding configuration is used.

    So, you'd want to put that .php ahead of the site-based handler.