I am trying to redirect a bunch of old URLs into new URls with the map directive. I am able to do the simple ones but kinda stuck on the ones with query parameters.
I need to do this
/people.php?personid=20 -> /people/20
/events.php/eventid=20 -> /event/20
/info.php?name=john&age=20 -> /person/john/20
I've got a map directive
map $request_uri $redirected_uri {
~^people.php\?personid=(.*)^ /people/$1?;
}
But doesn't seem to work. Any help would be appreciated. Thanks in advance.
My server block has this code
if ($redirected_uri) {
rewrite ^ $redirected_uri permanent;
}
Also, I am trying to do the following as well rewrite /people/20 back to people.php?personId=20 So, for that, I have this
map $request_uri $new_uri {
default 0
~^/people/(.*) /people.php?personId=$1;
}
and then in server block
if ($new_uri) {
rewrite ^ $new_uri last; // this doesn't work, throws 404
}
The common way to solve this looks something like this:
map $request_uri $redirect {
default 0;
~^/people.php\?personid=(\d+)^ /people/$1;
...
}
server {
...
if ($redirect) {
set $args '';
return 301 $redirect;
}
I have limited the capture group after personid=
to digits: \d+
The numeric capture goes out of scope as soon as another regular expression is evaluated, so the rewrite
statement itself wipes the value of $1
from the previous map
statement.
You could use a return
statement instead:
if ($redirected_uri) {
return 301 $redirected_uri;
}
Or better still, use a named capture in the map
:
map $request_uri $redirected_uri {
~^/people\.php\?personid=(?<personid>.*)$ /people/$personid;
}
Note also that Nginx URIs begin with a leading /
, you had an unescaped .
, and the correct anchor for the end of a regular expression is $
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.