Nginx启用了SSL后,tomcat里的HttpServletRequest检测不到scheme解决

2021-02-21 16点热度 0人点赞 0条评论

前言

之前web应用程序代码里用到HttpServletRequest.getScheme()得到的是http,但是启用了nginx的SSL后,确得到的不是https

如何配置Nginx和Tomcat整合,请看:https://blog.terrynow.com/2021/02/13/linux-nginx-tomcat-config-load-balance/

如何在nginx启用SSL,请看:https://blog.terrynow.com/2021/02/15/nginx-https-ssl-config/

下面解决如何让HttpServletRequest.getScheme()得到正确的scheme

配置tomcat 在conf/server.xml下,<Host/>下,看下面『加入如下代码』部分
<Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

    <!-- SingleSignOn valve, share authentication between web applications
         Documentation at: /docs/config/valve.html -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
    -->

    <!-- Access log processes all example.
         Documentation at: /docs/config/valve.html
         Note: The pattern used is equivalent to using pattern="common" -->
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log" suffix=".txt"
           pattern="%h %l %u %t &quot;%r&quot; %s %b" />

    <!-加入如下代码--->
    <Valve className="org.apache.catalina.valves.RemoteIpValve"
    remoteIpHeader="X-Forwarded-For"
    protocolHeader="X-Forwarded-Proto"
    protocolHeaderHttpsValue="https"/>

</Host>
配置nginx 在config ssl的地方,看下面『加入如下代码』部分
location / {
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    #加入如下代码
    proxy_set_header X-Forwarded-Proto  $scheme;
    proxy_pass http://127.0.0.1:8080;
}

好了,重启tomcat和nginx,就可以得到正确的scheme了

Terry

记录开发运维过程中遇到的坑以及解决方案,干货分享

文章评论

*

code