【问题标题】:Nginx: rewrite port in url from reverse proxie'd appNginx:从反向代理的应用程序重写 url 中的端口
【发布时间】:2020-03-13 02:00:17
【问题描述】:

所以我设置了一个反向代理来隧道我的应用程序。

不幸的是,应用程序认为它是通过 http 而不是 https 提供的,并给出了端口 80 的 URL。

如何在 nginx 反向代理中处理这个问题? (可能通过重写)


当我进入页面时:

https://my.server.com 

index.php 加载,一切正常

点击后我有一个这样的网址:

https://my.server.com:80/page/stuff/?redirect_to

这会在浏览器中引发错误,因为我的反向代理不在端口 80 上提供 SSL。

如何缓解这种情况?

我当前用于该站点的 nginx ssl vhost:

   ... ssl stuff ...
   add_header X-Frame-Options SAMEORIGIN;
   add_header X-Content-Type-Options nosniff;

   location / {
       proxy_pass http://localhost:22228;
       proxy_buffering off;
       proxy_redirect off;
       proxy_read_timeout 43800;
       proxy_pass_request_headers on;
       proxy_set_header Connection "Keep-Alive";
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $remote_addr;
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-Port 443;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection "upgrade";
       proxy_pass_header Content-Type;
       proxy_pass_header Content-Disposition;
       proxy_pass_header Content-Length;
       proxy_set_header X-Forwarded-Proto https;
   }

(是的,我知道我的请求标头看起来像一棵圣诞树????)

如果您显示解决此问题的文档在哪里以及该机制被称为什么,也可以加分。

【问题讨论】:

  • 欢迎来到stackoverflow。您是否需要在 HTTP 3xx 重定向标头或响应正文中重写这些 URL?
  • 嗨,谢谢伊万。我需要剥离端口并重写我的 nginx 向浏览器返回的响应中的 URL。
  • 而不是在 nginx 上重写响应,为什么不将应用程序更改为 http 端口 80 或 https 端口 443,这样就不会发生冲突?我的意思是,https 和端口 80 相处得不好。应用程序同时响应 https 和端口 80 很奇怪。
  • 嗨@flaixman。感谢您的输入。我已经尝试过,但不幸的是我无法更改应用程序的行为方式。这个问题是关于通过 nginx rewrite 找到解决方案的。

标签: nginx url https url-rewriting reverse


【解决方案1】:

要重写响应正文,您可以使用http_sub_module:

location / {
    proxy_pass http://localhost:22228;
    sub_filter_once off;
    sub_filter_types text/css application/javascript; # in addition to text/html
    sub_filter "//my.server.com:80/" "//my.server.com/";
}

很多人说(12)在使用sub_filter 指令时需要禁用压缩:

    proxy_set_header Accept-Encoding "";

对我来说,如果没有配置中的这一行,它可以正常工作,但它可以是 OpenResty 的一个功能,我使用它来代替 nginx。

如果您的应用生成带有明确指示域:端口的 HTTP 30x 重定向,您可以使用 proxy_redirect 指令重写 Location 标头值:

    proxy_redirect //my.server.com:80/ //my.server.com/;

【讨论】:

    猜你喜欢
    • 2019-11-04
    • 2014-02-01
    • 1970-01-01
    • 2022-01-07
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2016-01-30
    相关资源
    最近更新 更多