spring-boot+nginx+tomcat+ssl配置筆記

jopen 8年前發布 | 16K 次閱讀 Tomcat Nginx 應用服務器

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

來自: http://www.cnblogs.com/yang-wu/p/5107899.html

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!