Nginx代理HTTPS且非443端口,Tomcat为HTTP的配置

Nginx代理HTTPS且非443端口,Tomcat为HTTP的配置

  开始觉得这个配置需求非常的简单,不就是配置一下Nginx配置就搞定了。试了之后发现,出乎意料,所以打算将自己的经验记录下来。

  简单的描述一下场景,Nginx监听端口:8443,开启SSL;Tomcat启动的监听端口:8080,是HTTP。然后需要从Nginx的HTTPS代理到Tomcat的HTTP,基本的请求的流程图如下所示。
Nginx代理HTTPS且非443端口,Tomcat为HTTP的配置_第1张图片

方式一:
Nginx的HTTPS的配置
server {
    listen 8443;
    server_name test;
    ssl on;
    ssl_certificate   /usr/local/cert/test.pem;
    ssl_certificate_key  /usr/local/cert/test.key;
    ssl_session_timeout 30m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    
    location / {
        proxy_pass http://127.0.0.1:8080;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		# 非默认端口需要添加$server_port
        proxy_set_header Host $host:$server_port; 
	    proxy_set_header X-Real-IP $remote_addr; 
        proxy_redirect off;
    }
}
Tomcat的配置

需要在Engine里面添加配置如下:

<Valve className="org.apache.catalina.valves.RemoteIpValve"
                remoteIpHeader="x-forwarded-for"
                remoteIpProxiesHeader="x-forwarded-by"
                protocolHeader="x-forwarded-proto"
                protocolHeaderHttpsValue="https"
                httpsServerPort="8443"/>

  上面的 protocolHeaderHttpsValue="https"httpsServerPort="8443"的配置很关键,如果只配置了https这个,则Nginx访问后,如果应用重定向了则会重定向到443端口,而我们Nginx的端口实际应该是8443,导致访问到了443;所以httpsServerPort的配置就很关键了,这个配置指定了代理服务器的端口是8443,合起来的意思,如果http请求到来,则重定向到该端口,而不是443,而且如果代理服务器是https,则重定向的到https

方式二:
Nginx的HTTPS的配置
server {
    listen 8443;
    server_name test;
    ssl on;
    ssl_certificate   /usr/local/cert/test.pem;
    ssl_certificate_key  /usr/local/cert/test.key;
    ssl_session_timeout 30m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    
    location / {
        proxy_pass http://127.0.0.1:8080;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		# 非默认端口需要添加$server_port
        proxy_set_header Host $host:$server_port; 
	    proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Host $http_host;
        #这个很关键
        proxy_set_header X-Forwarded-Port $server_port;
        proxy_redirect off;
    }
}
Tomcat的配置

在 Engine 中添加如下 valve 配置:

<Valve className="org.apache.catalina.valves.RemoteIpValve"
    portHeader="x-forwarded-port"
    protocolHeader="x-forwarded-proto"
    proxiesHeader="x-forwarded-by"
    remoteIpHeader="x-forwarded-for"/>
参考

https://www.jianshu.com/p/f4ec9b3afb63

https://blog.csdn.net/radic_feng/article/details/6720059

你可能感兴趣的:(Nginx,HTTPS,HTTP,Tomcat,Nginx)