I am new to Nginx and am trying to setup rewrite rules for my Nginx virtual hosts.
/{firstname}-{lastname}.php to be rewritten to /Individual.php?firstname={firstname}&lastname={lastname}
/{firstname}-{lastname}-Info.php?Id=123 to be rewritten to /Individual-Info.php?Id={id}
That's the happy-case scenario. Sometimes, there might be a middle name as well e.g.
{firstname}-{middle}-{lastname}.php to be rewritten to Individual.php?firstname={firstname}&middle={middle}&lastname={lastname}
/{firstname}-{middle}-{lastname}-Info.php?Id=123&otherparam={otherparam} to be rewritten to /Individual-Info.php?Id={id}&otherparam={otherparam}
And sometimes, there might just be the last name
{lasname}.php to rewrite to Individual.php?lastname={lastname}
I have read the docs on the rewrite module, but I guess I am just struggling with the right regex, so this might be more of a regex question, but any help would be appreciated.
You need to order the rewrites so that the more specific match occurs before the less specific match. Do -Info first, then three names, then two names, then one name.
The rewrites are ambiguous, and there is a risk of a redirection loop, particularly for Mr Individual. You should probably place the rewrite statements inside your existing location ~ \.php$ block and use the break suffix. See this document for details.
For example:
location ~ \.php$ {
rewrite -Info\.php$ /Individual-Info.php break;
rewrite ^/(.*)-(.*)-(.*)\.php$ /Individual.php?firstname=$1&middle=$2&lastname=$3 break;
rewrite ^/(.*)-(.*)\.php$ /Individual.php?firstname=$1&lastname=$2 break;
rewrite ^/(.*)\.php$ /Individual.php?lastname=$1 break;
...
}
In response to your comment, you can rewrite only .php URIs which do not already exist by using try_files with a named location.
For example:
location ~ \.php$ {
try_files $uri @rewrite;
...
}
location @rewrite {
rewrite -Info\.php$ /Individual-Info.php last;
rewrite ^/(.*)-(.*)-(.*)\.php$ /Individual.php?firstname=$1&middle=$2&lastname=$3 last;
rewrite ^/(.*)-(.*)\.php$ /Individual.php?firstname=$1&lastname=$2 last;
rewrite ^/(.*)\.php$ /Individual.php?lastname=$1 last;
return 404;
}
Notice that you will need to use rewrite...last instead of rewrite...break. The try_files statement is added (or modified) within your existing location ~ \.php$ block.