【问题标题】:Nginx URL masking to a different domainNginx URL 屏蔽到不同的域
【发布时间】:2015-02-23 01:13:20
【问题描述】:

关于 SO 有一些类似的问题,但没有一个完全是我的问题,到目前为止,我没有运气尝试调整他们的答案。

我想将 URL http://sub.example.com 映射到 https://123.12.12.12/path,这样浏览器仍然会显示 URL http://sub.example.com

我的 Nginx 配置文件看起来像,

server {
    listen 80;
    server_name sub.example.com;

    location / {
        proxy_pass https://123.12.12.12;
        rewrite ^/$ /path last;
    }
}

路由在这里有效,但显示的 URL 是 http://sub.example.com/path。如何让它只显示http://sub.example.com

【问题讨论】:

  • 你会被重定向到http://sub.example.com/path吗?
  • 是的,不过我如何做到http://sub.example.com
  • 你需要消除重定向
  • 如何消除重定向?

标签: nginx rewrite


【解决方案1】:
server {
    listen 80;
    server_name sub.example.com;

    location / {
        proxy_pass https://123.12.12.12/path;
    }
}

这就是它的工作原理。如果 proxy_pass 包含位置部分 - 当前位置将被替换为指定的。 http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

但它只对 http 请求和 http 重定向有帮助。如果应用程序创建带有链接https://123.12.12.12 的html - 它仍然没有改变。在这种情况下,您可以尝试 ngx_http_sub_module。

【讨论】:

  • 如果我想将 HOST 标头传递给后端并且后端主机没有 DNS 名称怎么办?这也可能吗?
  • @VsMaX 你可以使用proxy_set_header Host somevalue.com; 或者,如果你需要传递前端主机,传递$host 变量proxy_set_header Host $host;
  • 问题是,当我设置proxy_set_header Host somevalue.com; 时,它仍然会对该不存在的主机名进行 DNS 查询。然后 nginx 失败,找不到错误的 DNS 名称...
  • @VsMaX 您的proxy_pass 是否带有IP 地址? proxy_set_header 不应该解析域,检查配置的其他部分
  • @DmitryMiksIr 我有类似的问题,尝试了您的解决方案,但是当显示来自proxy_pass 域的内容时,它也在使用该域上不存在的/path,所以我找不到页面.如何停止将/path 发送到新的屏蔽域?更具体地说,我正在尝试从 example.com/pathpath.example.com 的屏蔽重定向(wordpress 在这里运行)
【解决方案2】:

我是这样做的:

server {
    listen 80;
    listen [::]:80;
    listen 443 http2 ssl;
    listen [::]:443 http2 ssl;

    server_name domain1;

    if ($request_method ~* OPTIONS|GET|HEAD) {
        return 301 https://domain2$request_uri;
    }

    location ~* api {
        proxy_pass https://domain2$request_uri;
    }
}

因为 post-requests 在重定向时会导致 405 错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2021-11-23
    • 2018-10-21
    • 2018-04-19
    相关资源
    最近更新 更多