阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

Spring Boot+Nginx+Tomcat+SSL配置笔记

174次阅读
没有评论

共计 1842 个字符,预计需要花费 5 分钟才能阅读完成。

如果你的 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 端口就只能被本机访问了,其它机器访问不到。

Spring Boot 的详细介绍 :请点这里
Spring Boot 的下载地址 :请点这里

本文永久更新链接地址 :http://www.linuxidc.com/Linux/2016-01/127134.htm

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-01-21发表,共计1842字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中