【问题标题】:nginx rewrite preserving CGI query params (with a hash anchor)nginx 重写保留 CGI 查询参数(带有哈希锚)
【发布时间】:2019-11-05 17:21:17
【问题描述】:

对于我的 www.example.com nginx 配置,我有这些重写规则:

rewrite ^/foo$       https://one.example.com/page#one     permanent;
rewrite ^/foo(\?.*)$ https://two.example.com/page$1#two   permanent;

rewrite ^/bar$       https://three.example.com/page#one   permanent;
rewrite ^/bar\?(.*)$ https://four.example.com/page?$1#two permanent;

http://www.example.com/foo 的请求正确重定向到https://one.example.com/page#one

http://www.example.com/bar 的请求正确重定向到https://three.example.com/page#one

http://www.example.com/foo?extra=yes 的请求不正确 重定向到https://one.example.com/page#one?extra=yes(我希望它转到https://two.example.com/page?extra=yes#two)。

http://www.example.com/bar?extra=yes 的请求不正确 重定向到https://three.example.com/page#one?extra=yes(我希望它转到https://four.example.com/page?extra=yes#two)。

如何重定向到复制 CGI 参数并链接到目标页面中特定锚点的页面?

【问题讨论】:

    标签: nginx url-rewriting


    【解决方案1】:

    在将查询字符串组装成替换字符串时,rewrite 指令似乎无法正确处理 # 片段。

    您可以通过在替换字符串中添加尾随? 来防止rewrite 追加查询字符串。因此,您可以使用内置变量$is_args$args 构造正确的结果。

    例如:

    rewrite ^/foo$ https://one.example.com/page$is_args$args#one? permanent;
    

    详情请见this document

    请注意,查询字符串不是用于匹配 rewritelocation 语句的规范化 URI 的一部分,因此您的 ^/foo(\?.*)$ 正则表达式将不起作用。

    【讨论】:

    • 这似乎可行,但我看不到 nginx 文档中的哪些地方不能使用我的示例 twofouronethree 正在捕获所有内容) .这 依赖 $ 匹配 rewrite 操作的结尾,这被记录为“URI”,在 nginx 文档中的其他地方“URI”表示“带有 CGI 参数的完整请求”。所以我很犹豫接受这个,现在原样。如果没有其他更好的答案,我会的。
    • 这是mentioned here Nginx“只测试没有参数的请求行的URI部分”。
    • 该评论是针对location 指令的。在别处可能是这样,但该声明与别处无关。
    猜你喜欢
    • 2017-05-23
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 2017-03-17
    相关资源
    最近更新 更多