nginx 使用地图重定向多个 URL [英] nginx redirect multiple URLs with map
问题描述
我正在尝试使用 map 指令将一堆旧 URL 重定向到新 URL.我能够做简单的,但有点卡在带有查询参数的那些上.
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.
我需要这样做
/people.php?personid=20 -> /people/20
/events.php/eventid=20 -> /event/20
/info.php?name=john&age=20 -> /person/john/20
我有一个地图指令
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;
}
此外,我也在尝试执行以下操作将/people/20 改写回 people.php?personId=20所以,为此,我有这个
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;
}
然后在服务器块
if ($new_uri) {
rewrite ^ $new_uri last; // this doesn't work, throws 404
}
推荐答案
只要计算另一个正则表达式,数字捕获就会超出范围,因此 rewrite
语句本身会擦除 $1
来自前面的 map
语句.
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.
您可以改用 return
语句:
if ($redirected_uri) {
return 301 $redirected_uri;
}
或者更好的是,在 map
中使用命名捕获:
Or better still, use a named capture in the map
:
map $request_uri $redirected_uri {
~^/people\.php\?personid=(?<personid>.*)$ /people/$personid;
}
另请注意,Nginx URI 以 /
开头,您有一个未转义的 .
,正则表达式末尾的正确锚点是 $代码>.
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 $
.
这篇关于nginx 使用地图重定向多个 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!