Nginx + Tomcat + HTTPS 配置不需要在 Tomcat 上启用 SSL 支持

Nginx SSL+tomcat集群 Nginx tomcat no 不用https

最近做了个Web项目, 架构上使用了 Nginx +tomcat 集群, 且全站HTTPS,用nginx 做负载,nginx和tomcat 使用内网http通信,遇到http css,js静态资源被浏览器拦截问题,网上搜索到的很多文章在描述 Nginx + Tomcat 启用 HTTPS 支持的时候,都必须在 Nginx 和 Tomcat 两边同时配置 SSL 支持,今天做个总结。

遇到问题
  1. nginx强制使用https访问(http跳转到https)
  2. http的js,css 等静态资源被浏览器拦截(http不被信任)

最后的解决方案

首先解决第一个问题全站https
参考
三种方式,跟大家共享一下

nginx的rewrite方法

server {  
listen  192.168.1.111:80;  
server_name test.com;  
rewrite ^(.*)$  https://$host$1 permanent;
}  

nginx的497状态码,我选择了这种方式

server {  
    listen       192.168.1.11:443;  #ssl端口  
    listen       192.168.1.11:80;   #用户习惯用http访问,加上80,后面通过497状态码让它自动跳到443端口  
    server_name  test.com;  
    #为一个server{......}开启ssl支持  
    ssl                  on;  
    #指定PEM格式的证书文件   
    ssl_certificate      /etc/nginx/test.pem;   
    #指定PEM格式的私钥文件  
    ssl_certificate_key  /etc/nginx/test.key;  

    #让http请求重定向到https请求   
    error_page 497  https://$host$uri?$args;  
}  

index.html刷新网页

<html>  
<meta http-equiv="refresh" content="0;url=https://test.com/">  
</html> 

当http访问到index.html时候自动跳转到https


接下来解决第二个问题
如果tomcat 和nginx 双方没有配置X-Forwarded-Proto tomcat就不能正确区分实际用户是http 还是https,导致tomcat 里配置的静态资源被认为是http而被浏览器拦截,request.getScheme()总是 http,而不是实际的http或https

分别配置一下 Nginx 和 Tomcat ,果然好了。
配置 Nginx 的转发选项:

 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;  

配置Tomcat server.xml 的 Engine 模块下配置一个 Valve:

<Valve className="org.apache.catalina.valves.RemoteIpValve"  
remoteIpHeader="X-Forwarded-For"  
protocolHeader="X-Forwarded-Proto"  
protocolHeaderHttpsValue="https"/>  

非80端口配置
Nginx增加以下配置
proxy_set_header Host $host:$server_port; 非80端口 ,用80端口时 不需要$server_port
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;

Tomcat server.xml配置
<Engine name="Catalina" defaultHost="localhost">
<Valve className="org.apache.catalina.valves.RemoteIpValve"
remoteIpHeader="X-Forwarded-For"
protocolHeader="X-Forwarded-Proto"
protocolHeaderHttpsValue="https" httpsServerPort="7001"/> 非80端口时,必须增加httpsServerPort配置,不然request.getServerPort()方法返回 443.
</Engine>

关于 RemoteIpValve,可以阅读下 doc

http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/valves/RemoteIpValve.html

  • 6
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值