Nginx location regex and try_files

nginxredirect

Trying to set up an inherited nginx to do my bidding, but failing a bit at doing so.

I have the typical nginx WordPress setup:

location / {
 try_files $uri $uri/ /index.php?q=$uri&$args;
}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
 location ~ \.php$ {
   try_files $uri =404;
   fastcgi_pass unix:/var/run/php5-fpm.sock;
   fastcgi_index index.php;
   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
   include fastcgi_params;
}

So far, so good. But I also need to check for old URLS from a previous install that follow this pattern:

^(ninos|familia|hogar|mujeres|hombres)(-[a-z-]+){1,3}\.php

And direct those to index.php with its parameters intact, since WP will handle them with a proper 301 redirect to the new URL.

How should I do this? Should I nest another location inside the location ~ \.php$? Or have another separate location block outside, replicating the configuration of the location ~ \.php$? (Minus the "try_files $uri =404"; which I guess it'll break everything down).

Many thanks and regards. Nginx newbie. Tried the docs, but left me confused…

Best Answer

Ended up fixing it by adding an additional location block as this:

location ~ "(ninos|familia|hogar|mujeres|hombres)(-[a-z-]+){1,3}\.php$" {
    try_files $uri /index.php?$args;
 }

Hopefully I'm not breaking anything else... :P

Update:

After @tero-kilkanen helpful suggestion, I replaced the above with:

location ~ "(ninos|familia|hogar|mujeres|hombres)(-[a-z-]+){1,3}\.php$" {
    rewrite ^ /index.php?$args last;
 }