【发布时间】:2019-06-13 23:51:02
【问题描述】:
我有一个这样的 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&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;
}
}
注意:这是一个单页应用程序,如果有帮助的话。
【问题讨论】:
-
试试:
rewrite ^/(v\d+)(?:/(.*))?$ /$2?version=$1 redirect; -
@RichardSmith 感谢您的帮助!应该放在
location ~*块或location = /块中还是直接在server块下面? -
@RichardSmith 太接近了。这是它所在的 URL:
http://example.com:8080//getting-started?version=v2&product=life。唯一的问题是它添加了一个额外的/和端口号。那就是将rewrite放在location ~*块中。 -
我在测试时看不到
//。您是否完全按照书面说明使用了我的正则表达式?rewrite可以进入server块或匹配的location块。location = /块将不起作用,因为它只匹配 URI/。除非您使用port_in_redirect off;,否则会包含端口号。 -
@RichardSmith 我明白了,谢谢!你想把它作为答案,以便我标记它吗?
标签: nginx nginx-location nginx-config