如果你的tomcat应用需要采用ssl来加强安全性,一种做法是把tomcat配置为支持ssl,另一种做法是用nginx反向代理tomcat,然后把nginx配置为https访问,并且nginx与tomcat之间配置为普通的http协议即可。下面说的是后一种方法,同时假定我们基于spring-boot来开发应用。

一、配置nginx:

server {
listen 80;
listen 443 ssl;
server_name localhost; ssl_certificate server.crt;
ssl_certificate_key server.key; location / {
proxy_pass http://localhost:8080;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Port $server_port;
}
}

这里有三点需要说明:

1、nginx允许一个server同时支持http和https两种协议。这里我们分别定义了http:80和https:443两个协议和端口号。如果你不需要http:80则可删除那行。

2、nginx收到请求后将通过http协议转发给tomcat。由于nginx和tomcat在同一台机里因此nginx和tomcat之间无需使用https协议。

3、由于对tomcat而言收到的是普通的http请求,因此当tomcat里的应用发生转向请求时将转向为http而非https,为此我们需要告诉tomcat已被https代理,方法是增加X-Forwared-Proto和X-Forwarded-Port两个HTTP头信息。

二、接着再配置tomcat。基于spring-boot开发时只需在application.properties中进行配置:

server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
server.tomcat.port-header=X-Forwarded-Port
server.use-forward-headers=true

该配置将指示tomcat从HTTP头信息中去获取协议信息(而非从HttpServletRequest中获取),同时,如果你的应用还用到了spring-security则也无需再配置。

此外,由于spring-boot足够自动化,你也可以把上面四行变为两行:

server.tomcat.protocol_header=x-forwarded-proto
server.use-forward-headers=true

下面这样写也可以:

server.tomcat.remote_ip_header=x-forwarded-for
server.use-forward-headers=true

但不能只写一行:

server.use-forward-headers=true

具体请参见http://docs.spring.io/spring-boot/docs/1.3.0.RELEASE/reference/htmlsingle/#howto-enable-https,其中说到:

server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
The presence of either of those properties will switch on the valve

此外,虽然我们的tomcat被nginx反向代理了,但仍可访问到其8080端口。为此可在application.properties中增加一行:

server.address=127.0.0.1

这样一来其8080端口就只能被本机访问了,其它机器访问不到。

最新文章

  1. [C1] C1FlexGrid 行列增删&单元格合并拆分
  2. Golang(笔记) 顺序编程
  3. 关于MySQL密码你应该知道的那些事
  4. J2EE中关于tomcat的maxIdle、maxActive、maxActive相关配置
  5. Leetcode 9 Palindrome Number 数论
  6. Android内存溢出解决方案(OOM)
  7. 笔试面试题-小米Git
  8. SQL Server数据类型
  9. leetcode修炼之路——350. Intersection of Two Arrays II
  10. 【测试技术】ant在测试中的使用@文件以及目录的读写删和复制
  11. JavaScript 中的面向对象的初步认识
  12. 交换右ctrl和capslock
  13. 【Linux】CentOS系统
  14. chrome浏览器调试功能之后端篇
  15. 深入分析动态管理Fragment
  16. unix时间戳转换成标准时间(c#)
  17. IoC和AOP的理解
  18. codeforces850E Random Elections
  19. 设计模式之Template Method模式
  20. 编写一个简单的基于jmespath 的prometheus exporter

热门文章

  1. 在CDHtmlDialog中处理WindowClosing
  2. 发几个速度快可以用的google IP,谷歌IP(转)
  3. Hdu2437-Jerboas(取余数判重搜索)
  4. python高级编程(第12章:优化学习)2
  5. web前端之 CSS引入第三方插件
  6. (转)25个增强iOS应用程序性能的提示和技巧--中级篇
  7. SEO 外链 内链 的定义
  8. FullCalendar 的学习笔记(二)
  9. (转)javascript中 window.location= window.location;是什么意思
  10. 公司项目笔记-导出excel