nginx反向代理tomcat
背景
因客户需要对某个应用对外开放访问,需要有ssl安全协议,又考虑到后面可能还会有多个应用对外开放访问,因此决定用nginx来配置ssl证书,通过nginx来转发到后台应用。
环境
后台应用服务:tomcat7
负载均衡服务:nginx1.26.3
配置
nginx.conf
# HTTPS server
server {
# listen 443 ssl;
listen 8088 ssl;
http2 on;
# server_name localhost;
server_name *.example.com;
ssl_certificate pem文件位置;
ssl_certificate_key key文件位置;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
# root html;
# index index.html index.htm;
proxy_pass http://127.0.0.1:8080;
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;
}
}
注意,我上面的ssl的端口为8088,不是一般的443
tomcat里的server.xml
.....省略
<Connector port="8080" protocol="HTTP/1.1" maxThreads="2000"
connectionTimeout="20000" maxHttpHeaderSize="3145728"
redirectPort="8443"
/>
....省略
<Valve className="org.apache.catalina.valves.RemoteIpValve"
protocolHeaderHttpsValue="https"
remoteIpHeader="X-Forwarded-For" protocolHeader="X-Forwarded-Proto" />
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
现在配置完毕,重启没问题,可以用https://xxxx:8088/index打开首页
到此,你一定觉得没问题了,我当时也这么觉得,结果一登录。。。无法打开主页
因为地址变成了https://xxxx/main 端口没了!!!
解决过程
首先,我把nignx配置文件的端口改回443,打开首页登录都没问题,好吧,已经确定是重定向的问题。那么为什么重定向的时候端口号会没呢。经过一通查找,终于在各路网友的帖子和tomcat的官方api找到了答案
当用https转发时,tomcat默认配置的端口是443,因此这里只需要把端口改成8088就行了,如下
<Valve className="org.apache.catalina.valves.RemoteIpValve"
protocolHeaderHttpsValue="https" httpsServerPort="8088"
remoteIpHeader="X-Forwarded-For" protocolHeader="X-Forwarded-Proto" />
在之前的server.xml加上httpsServerPort="8088"即可
将nginx的ssl配置改回8088端口,重启,ok,首页和登录跳转都没问题了
插曲
因为系统中还集成了oss,代码里面还是http,因此用https访问的时候会报错
因此相关的代码要改成https协议请求oss
ClientConfiguration cfg = new ClientConfiguration();
cfg.setProtocol(Protocol.HTTPS);
OSSClient client = new OSSClient(endpoint, accessId, accessKey,cfg);
这样就大功造成了!
相关参考:
nginx反向代理tomcat 时,出现https redirect后变成http的问题解决方法 - 滚动的蛋 - 博客园
nginx中https请求转发为本服务器的tomcat的http请求_nginx 转发tomcat-CSDN博客
Apache Tomcat 7.0.109 API Documentation
OSS generatePresignedUrl如何返回一个https的URL_问答-阿里云开发者社区
2024阿里云免费版SSL证书申请流程,跟着教程一步步,非常简单!-阿里云开发者社区
nginx配置https转发到tomcat(使用自签名的证书)-腾讯云开发者社区-腾讯云