Reputation: 801
I try to move my server from Apache towards a Nginx based setting. However, I get into problems getting a part of my htaccess Apache magic to work in Nginx.
The .htaccess code I would like to transfer is:
RewriteRule ^([a-zA-Z0-9_]+)/$ /index.php?page=$1 [L,QSA]
RewriteRule ^([a-zA-Z0-9_]+).html$ /index.php?page=$1 [L,QSA]
RewriteRule ^([a-zA-Z0-9_]+)/([0-9]+)/.*/([a-zA-Z0-9_]+)$ /index.php?page=$1&id=$2&sub=$3 [L,QSA]
RewriteRule ^([a-zA-Z0-9_]+)/([0-9]+)/.*$ /index.php?page=$1&id=$2 [L,QSA]
I used an online converter that gave me the following location block:
location / {
rewrite ^/([a-zA-Z0-9_]+)/$ /index.php?page=$1 break;
rewrite ^/([a-zA-Z0-9_]+).html$ /index.php?page=$1 break;
rewrite ^/([a-zA-Z0-9_]+)/([0-9]+)/.*/([a-zA-Z0-9_]+)$ /index.php?page=$1&id=$2&sub=$3 break;
rewrite ^/([a-zA-Z0-9_]+)/([0-9]+)/.*$ /index.php?page=$1&id=$2 break;
}
Sadly, I'm only able to get a single location rewrite to be working at a time (the one I put "last;" behind). I don't seem to be able to do this dynamic rewriting of a multiple subfolder URL into arguments for a single PHP script.
Any help on this? What is the Nginx way of doing such a rewrite? I tried using several location's for different subfolders but I would rather have a generic solution that work no-matter what url's are thrown at it.
Upvotes: 0
Views: 1287
Reputation: 846
Use a different location block for each rule:
location ~ ^/[a-zA-Z0-9_]+/$ {
rewrite ^/([a-zA-Z0-9_]+)/$ /index.php?page=$1 last;
}
location ~ ^/[a-zA-Z0-9_]+.html$ {
rewrite ^/([a-zA-Z0-9_]+).html$ /index.php?page=$1 last;
}
location ~ ^/[a-zA-Z0-9_]+/[0-9]+/.*/[a-zA-Z0-9_]+$ {
rewrite ^/([a-zA-Z0-9_]+)/([0-9]+)/.*/([a-zA-Z0-9_]+)$ /index.php?page=$1&id=$2&sub=$3 last;
}
location ~ ^/[a-zA-Z0-9_]+/[0-9]+/.*$ {
rewrite ^/([a-zA-Z0-9_]+)/([0-9]+)/.*$ /index.php?page=$1&id=$2 last;
}
location = /index.php {
# your proxy rules here...
}
The rewrite rules above use the last option, which is explained in the nginx docs:
last
stops processing the current set of ngx_http_rewrite_module
directives and starts a search for a new location matching the
changed URI;
Upvotes: 2