Nginx删除URL路径并将其作为查询参数放置
我有这样一个URL:Nginx删除URL路径并将其作为查询参数放置,nginx,nginx-location,nginx-config,Nginx,Nginx Location,Nginx Config,我有这样一个URL:https://example.org/v2?product=lifesum我需要将其改写为:https://example.org?version=v2&product=lifesum。URL可能有或多或少的查询参数,所以我需要保留所有这些参数。另外,/v2实际上可能不存在,因此我需要处理这些情况。以下是一些应如何重写的示例: https://example.org/v2?product=lifesum-> https://example.org?version=v2&p
https://example.org/v2?product=lifesum
我需要将其改写为:https://example.org?version=v2&product=lifesum
。URL可能有或多或少的查询参数,所以我需要保留所有这些参数。另外,/v2
实际上可能不存在,因此我需要处理这些情况。以下是一些应如何重写的示例:
->https://example.org/v2?product=lifesum
https://example.org?version=v2&product=lifesum
->https://example.org?product=lifesum
https://example.org?product=lifesum
->https://example.org/v13/foo/bar?product=lifesum
https://example.org/foo/bar?version=v13&product=lifesum
->https://example.org/v1113
https://example.org?version=v1113
->https://example.org
https://example.org
# HTTP Server
server {
# port to listen on. Can also be set to an IP:PORT
listen 8080;
# This is my attempt to match and rewrite
location ~* (\/v\d+) {
rewrite (\/v\d+) /?api_version=$1 break;
}
location = / {
# I have also tried this rewrite but iit is not working either
rewrite (\/v\d+) /?api_version=$1 break;
try_files $uri $uri/ /index.html;
}
}
注意:这是一个单页应用程序,如果有帮助的话。要满足您的所有要求,您需要捕获版本字符串后面的URI部分 例如:
rewrite ^/(v\d+)(?:/(.*))?$ /$2?version=$1 redirect;
redirect
标志使Nginx使用302状态的外部重定向(有关详细信息,请参阅)。SPA需要外部重定向才能看到新的URI
rewrite
语句可以放在外部server
块中,也可以放在与原始URI匹配的location
块中(例如:location~*^/v\d
)
要避免Nginx向重定向的URI添加端口号,请使用:
port_in_redirect off;
有关详细信息,请参见。尝试:
重写^/(v\d+(:/(.*))?$/$2?版本=$1重定向代码>@RichardSmith谢谢你的帮助!这应该放在location~*
块或location=/
块中,还是直接放在服务器
块下?@RichardSmith,非常接近。这是它登陆的网址:http://example.com:8080//getting-已启动?版本=v2&产品=寿命
。唯一的问题是它添加了一个额外的/
和端口号。也就是说,rewrite
放在location~*
块中。我测试它时没有看到/
。你是否完全按照我写的那样使用我的正则表达式?重写
可以进入服务器
块或匹配的位置
块。location=/
块将不工作,因为它只匹配URI/
。端口号包括在内,除非您使用。@RichardSmith我知道了,谢谢!你想回答这个问题,这样我就可以做标记了?