【问题标题】:Nginx remove URL path and place it as a query parameterNginx 移除 URL 路径并将其作为查询参数
【发布时间】: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


【解决方案1】:

为了满足您的所有要求,您需要捕获版本字符串之后的 URI 部分。

例如:

rewrite ^/(v\d+)(?:/(.*))?$ /$2?version=$1 redirect;

redirect 标志使 Nginx 使用具有 302 状态的外部重定向(有关详细信息,请参阅this document)。 SPA 需要外部重定向才能看到新的 URI。

rewrite 语句可以放置在外部 server 块中或与原始 URI 匹配的 location 块中(例如:location ~* ^/v\d)。

为避免 Nginx 将端口号添加到重定向的 URI,请使用:

port_in_redirect off;

详情请见this document。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2010-12-25
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    相关资源
    最近更新 更多