若是你的tomcat应用须要采用ssl来增强安全性,一种作法是把tomcat配置为支持ssl,另外一种作法是用nginx反向代理tomcat,而后把nginx配置为https访问,而且nginx与tomcat之间配置为普通的http协议便可。下面说的是后一种方法,同时假定咱们基于spring-boot来开发应用。html
1、配置nginx: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; } }
这里有三点须要说明:spring
一、nginx容许一个server同时支持http和https两种协议。这里咱们分别定义了http:80和https:443两个协议和端口号。若是你不须要http:80则可删除那行。tomcat
二、nginx收到请求后将经过http协议转发给tomcat。因为nginx和tomcat在同一台机里所以nginx和tomcat之间无需使用https协议。安全
三、因为对tomcat而言收到的是普通的http请求,所以当tomcat里的应用发生转向请求时将转向为http而非https,为此咱们须要告诉tomcat已被https代理,方法是增长X-Forwared-Proto和X-Forwarded-Port两个HTTP头信息。bash
2、接着再配置tomcat。基于spring-boot开发时只需在application.properties中进行配置:app
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
此外,因为spring-boot足够自动化,你也能够把上面四行变为两行:spa
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端口就只能被本机访问了,其它机器访问不到。