【问题标题】:Nginx Https Redirect with Trailing Slash and Query Parameters带有斜杠和查询参数的 Nginx Https 重定向
【发布时间】:2019-03-07 11:14:06
【问题描述】:

我有一个 Nginx 服务器配置,它已经将 http 请求重定向到 https,但我正在尝试找出修改此代码或完全更改它以将 http 请求重定向到 https 的正确方法在 url 不包含时添加尾部正斜杠 /。这些重定向还应确保尽管重定向仍然存在查询参数。我已经看到我的类似问题的大多数答案都引用了^/(.*)/$ 作为添加正斜杠的代码,但我不确定如何使用它以及是否应该使用rewrite 而不是if。谁能帮我解惑?

nginx.config:

upstream nodejs {
    server 127.0.0.1:8081;
    keepalive 256;
}

server {
    listen 8080;

    if ($http_x_forwarded_proto = "http") { return 301 https://$host$request_uri; }

    location / {
        proxy_pass  http://nodejs;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP   $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    gzip on;
    gzip_comp_level 4;
    gzip_types text/html text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

}

目标:

http://www.example.com/page-one -> http://example.com/page-one/
http://example.com/page-two -> https://www.example.com/page-two/
https://www.example.com/page-three?page=2 -> https://www.example.com/page-three/?page=2

【问题讨论】:

  • rewrite 指令会将查询字符串附加到重写的 URL,除非添加了尾随 ?
  • 知道了。很高兴知道。你知道正确的rewrite 方法来实现我上面的要求吗?

标签: nginx redirect url-rewriting


【解决方案1】:

您的目标中的三个步骤都以不同的方式执行。第一步最好使用单独的server 块来实现。您已经在问题中进行了第二步。第三步使用rewrite 语句。

例如:

server {
    listen 8080 default_server;
    return http://example.com$request_uri;
}
server {
    listen 8080;
    server_name example.com;

    if ($http_x_forwarded_proto = "http") { return 301 https://$host$request_uri; }

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

    ...
}

现有的查询字符串也附加到重写的 URL。详情请见this document

【讨论】:

  • 理查德感谢您的回答。由于我将其作为脚本推广到多个域(例如http://staging.example.comhttps://www.example.com),是否有必要添加第一个严格标识主机名的服务器块?我在没有第一个块的情况下尝试了您的代码,rewrite 按预期工作,但看起来它正在向所有资产和 URL 添加正斜杠。我想我需要添加一个单独的行或修改重写以防止文件接收到这个。
  • 要实现目标 #1,您可以在 if 语句中的 $host 上使用正则表达式。 rewrite 规则处理每个 URI,不带尾随 /,那么资产的 URI 与需要尾随 / 的 URI 有何不同?
  • 感谢您的额外帮助。是否可以用$host 而不是if 语句切换http://example.com?资产的不同之处在于,这是在扩展后重写并破坏位置查找。例如。资产位于https://www.example.com/image/logo.svg,但重写是在.svghttps://www.example.com/image/logo.svg/ 之后添加/,并且图像呈现为损坏。
  • 您需要一个正则表达式,它只匹配那些需要尾随 / 的 URI。如果 $host 包含 www. 您将需要使用正则表达式来捕获非 www 主机名。
猜你喜欢
  • 1970-01-01
  • 2012-12-14
  • 2021-07-28
  • 2020-11-19
  • 2018-02-19
  • 2017-06-02
  • 2015-01-20
  • 2013-01-27
相关资源
最近更新 更多