nginx rewrites with exclusions
I have a site which recently changed its page structure to add the ability for multiple languages (/en/
for English, /fr/
for French). I have the following rewrite rules in my server {}
block:
try_files $uri $uri/ @abc;
location @abc {
if ($uri !~ "^/(.*)\/(.*)$") {
rewrite ^/(.*)$ /en/$1 permanent;
}
rewrite ^/(.*)\/(.*)$ /index.php?lang=$1&page=$2;
}
rewrite ^/$ /en/$1 permanent;
It's a little bit of a mess, but I can't seem to accomplish what I need:
- All links accessed should be checked to see if the file exists (works)
- All 'ol开发者_开发技巧d' links such as
/abc
should be 301'd to/en/abc
(works, but seems hackish) - The root of the site should be redirected to
/en/
(works) - Links in the format
/en/abc
should be sent toindex.php
as?lang=$1&page=$2
(this includes/en/abc/123
whereabc/123
is$2
anden
is$1
).$2
can have any length, such asabc/123/456
What I have 'seems' to work fine, but sub pages abc/123
seem to set $1
to en/abc
and $2
to 123
which isn't desired and results in a 404 error as the script can't find the page 123
. Thanks in advance for any answers!
Try this
try_files $uri $uri/ @abc;
location @abc {
if ($uri !~ "^/([^\/]*)\/([^\/]*)$") {
rewrite ^/(.*)$ /en/$1 permanent;
}
rewrite ^/([^\/]*)\/([^\/]*)$ /index.php?lang=$1&page=$2;
}
rewrite ^/$ /en/$1 permanent;
I have replace .*
with [^\/]*
.
精彩评论