【问题标题】:Nginx rewrite rule: add trailing slash before question markNginx重写规则:在问号前添加斜杠
【发布时间】:2016-11-11 16:01:43
【问题描述】:

在 Nginx 中,如何在重写规则的问号前添加斜杠?

我已成功在 URL 末尾添加斜杠。 A如下:

http://test/xx --> http://test/xx/

但我无法实现在问号前添加斜杠。如下:

http://test/xx?id=2 --> http://test/xx/?id=2

我尝试了以下方法:

server {

  listen 34044;

  # add trailing slash to url end
  rewrite ^([^.\?]*[^/])$ $1/ permanent;

  # add trailing slash before question mark
  rewrite "^(.*)([^/]{1})\?(.*)$" $1$2/?$3 permanent;

  location / {
    ...
  }
}

但它不会在问号前添加斜杠。

我想,我在第二个正则表达式中有一个错误,但我看不到它。请帮忙

【问题讨论】:

  • ? 标记查询字符串的开始,它不是locationrewrite 指令中使用的规范化URI 的一部分。有关详细信息,请参阅this document。因此,您重写的任何尾随 / 始终位于 ? 之前。
  • 啊!现在我明白了,非常感谢!回答我自己的问题.. ;)

标签: nginx url-rewriting


【解决方案1】:

在@richard-smith 发表评论后,我了解到我只需要一个正则表达式,如下所示:

rewrite ^([^.]*[^/])$ $1/ permanent;

它按我的需要工作:在所有 URL 中添加斜杠,包括 '?' 之前的斜杠符号。而且不会破坏资源链接,比如https://my-site/styles.css

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 2017-05-27
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多