Nginx+Tomcat实现https,监听非80/443端口

时间:2024-03-22 16:43:09

一、背景
1.1 tomcat + struts的项目
1.2 支持https,nginx做证书卸载,nginx与tomcat依旧是以http协议交互
1.3 服务监听的端口非80、443
1.4 后端获取服务地址:String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 

二、解决的问题
2.1 现象: 服务支持https后,登陆页返回的静态资源地址是443端口,但nginx、tomcat均未配置443端口
2.2 原因: 后端服务支持htps后,需要在tomcat里明确指定端口号-httpsServerPort,否则request.getServerPort()默认获取的是443

在未指明httpsServerPort时,图中红色区域端口为443

Nginx+Tomcat实现https,监听非80/443端口

三、完整配置

nginx配置:
server{
    listen 1234 ssl;
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_certificate      ../ssl/full_chain_rsa.crt;
    ssl_certificate_key  ../ssl/privateKey.key;
    access_log logs/access.log web_entry;

    location ~.*\.(html|htm|ico|png|jpg|jpeg|js|css|bmp)$ {
            limit_except GET POST OPTIONS{
                 deny all;
            }
            root /home/boco4a/hswx/;

    }

    location / {

            limit_except GET POST OPTIONS{
                deny all;
            }
            
            proxy_set_header Host $host:$server_port;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-Proto https;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_redirect off;

            proxy_pass http://127.0.0.1:11234;

    }
}

tomcat配置:
<Service name="Back">
                <Connector port="11234" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="1234" proxyPort="1234" URIEncoding="UTF-8" />
                <Connector port="2234" protocol="AJP/1.3" redirectPort="1234" />
                <Engine name="Catalina" defaultHost="localhost">z
                        <Realm className="org.apache.catalina.realm.LockOutRealm">
                                <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase" />
                        </Realm>

                <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">
                        <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"
                                remoteIpProxiesHeader="X-Forwarded-By"
                                protocolHeader="X-Forwarded-Proto"
                                httpsServerPort="1234"
                        />

                        <Context path="/test" docBase="/home/test11/test" reloadable="false" crossContext="true" />
                </Host>
                </Engine>
</Service>