【问题标题】:How to escape "?" in nginx rewrite rule output如何逃脱“?”在 nginx 重写规则输出
【发布时间】:2019-08-24 00:10:41
【问题描述】:

我正在尝试在nginx 中进行反向代理,将“/a/b?page=2”之类的前端页面重写为“/a/b%3fpage=2”的后端请求

我不知道如何让nginx 发出包含“%3f”的反向代理请求。

使用以下配置:

rewrite ^/one$ /a%3fb;
rewrite ^/two$ /a?b;
rewrite ^/three$ /a\?b;
  • /one 发出类似GET /a%253fb HTTP/1.0 的后端请求
  • /two 发出类似GET /a?b HTTP/1.0 的后端请求
  • /three 发出类似GET /a\?b HTTP/1.0 的后端请求

如何获得类似GET /a%3fb HTTP/1.0 的后端请求?

【问题讨论】:

  • @RichardSmith 我认为这是不同的。我在 RFC 中能找到的最好的就是你 only decode 'unreserved characters' for normalisation 和 ?是保留字符。当然 Chrome 以不同的方式对待它们,例如new URL("http://www.example.com/a%3fb").pathname === '/a%3fb'new URL("http://www.example.com/a?b").pathname === '/a'
  • 这似乎是可能的,但不使用rewrite 指令。将 URI(或包含该 URI 的变量)附加到 proxy_pass 指令将不受干扰地向上游传递。
  • @RichardSmith -- 区别在于“/a/b?page=2”的路径为“/a/b”和查询字符串,而/a/b%3fpage=2 的路径为“/a/b%3fpage=2”且没有查询细绳。在大多数网络服务器上,后者将提供一个名为“b?page=2”的文件(对于允许文件名中包含“?”的文件系统)

标签: nginx url-rewriting escaping reverse-proxy


【解决方案1】:

感谢@Richard Smith 的评论,我能够使用以下代码针对我的具体情况解决此问题:

location / {

  set $backend_uri $request_uri;
  if ($args ~* "page=(\d+)") {
    set $page $1;
    set $backend_uri $uri%3fpage=$1;
  }

  proxy_pass http://example.com$backend_uri;
}

我认为我还可以使用 lua rewrite 指令做一些更通用的事情,但我无法在 Amazon Linux 2 机器上安装 mod-lua,请参阅 https://serverfault.com/questions/961337/how-to-install-nginx-mod-lua-on-amazon-linux-2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多