【问题标题】:Incorrect redirect scheme in using nginx as reversed proxy使用 nginx 作为反向代理的重定向方案不正确
【发布时间】:2015-02-03 12:45:01
【问题描述】:

我使用nginx作为前端服务器,tomcat作为后端。客户通过 https 方案访问我的网站。例如:

https://example.com/app/test

Nginx 接收到这个并通过这个本地地址将请求传递给 tomcat:

http://localhost:8080/app/test

我的 nginx 配置:

location / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forward-For $remote_addr;
    proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forward-Proto $scheme;
    proxy_pass http://localhost:8080;
}

这很好用。但是,当我尝试使用重定向(http 302)时,它总是将 https 转换为 http。这是我的重定向代码:

response.sendRedirect("/app/redirect-test");

我期望将浏览器重定向到:

https://example.com/app/redirect-test

但它总是将浏览器重定向到:

http://example.com/app/redirect-test.

我还记录了标题以跟踪此问题:

host : example.com
x-real-ip : 180.168.202.246
x-forward-for : 180.168.202.246
x-forward-proto : https
connection : close
......

但我还是想不通。我尝试记录 request.getRequestURL(),然后我得到这个结果:

http://example.com/app/test

我该如何解决这个问题?

【问题讨论】:

  • 我意识到我犯了一个错误,X-Forward-For 应该是 X-Forwarded-For 而 X-Forward-Proto 应该是 X-Forwarded-Proto。但是在我修复之后,问题仍然存在。

标签: tomcat redirect nginx https


【解决方案1】:

我找到了解决方案。

nginx.conf

location / {
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://localhost:8080;
}

修改 Tomcat 的 server.xml Host 部分

<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">
<!-- blah blah blah -->
<Valve className="org.apache.catalina.valves.RemoteIpValve" remoteIpHeader="X-Forwarded-For" protocolHeader="X-Forwarded-Proto" protocolHeaderHttpsValue="https"/>
</Host>

去这个地方看详情:Tomcat Doc

【讨论】:

  • 救命稻草!谢谢。
猜你喜欢
  • 2019-03-12
  • 2016-04-11
  • 2019-05-23
  • 2020-05-31
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多