nginx反向代理springboot https下重定向問題

問題描述

項(xiàng)目采用springboot框架,內(nèi)嵌tomcat容器。前端采用nginx反向代理,當(dāng)部署了https以后出現(xiàn)的重定向(redirect)的問題。用nginx反向代理tomcat,然后把nginx配置為https訪問,并且nginx與tomcat之間配置為普通的http協(xié)議,當(dāng)后臺(tái)代碼定義時(shí)redirect,實(shí)際是重定向到了http下的地址,導(dǎo)致瀏覽器上無法訪問非https的地址。

解決方案

配置nginx

由于對(duì)tomcat而言收到的是普通的http請(qǐng)求,因此當(dāng)tomcat里的應(yīng)用發(fā)生轉(zhuǎn)向請(qǐng)求時(shí)將轉(zhuǎn)向?yàn)閔ttp而非https,為此我們需要告訴tomcat已被https代理,方法是增加X-Forwared-Proto和X-Forwarded-Port兩個(gè)HTTP頭信息。

    server {
        listen 443;
        server_name  localhost;

        ssl                  on;
        ssl_certificate      /ssl/test.pem;
        ssl_certificate_key  /ssl/test.key;
        ssl_session_timeout  5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;   
        ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";

        location / {
            proxy_pass http://agent;
            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;
        }
    }

配置tomcat

springboot配置參見Spring Boot Reference Guide-Use behind a front-end proxy server

基于spring-boot開發(fā)時(shí)只需在application.properties中進(jìn)行配置。
該配置將指示tomcat從HTTP頭信息中去獲取協(xié)議信息(而非從HttpServletRequest中獲取

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

以下是經(jīng)常被漏掉的配置,本人一開始就忘記配置導(dǎo)致不成功。因?yàn)槲业膎ginx的機(jī)器IP不在默認(rèn)允許IP列表里

Tomcat is also configured with a default regular expression that matches internal proxies that are to be trusted. By default, IP addresses in 10/8, 192.168/16, 169.254/16 and 127/8 are trusted. You can customize the valve’s configuration by adding an entry to application.properties, e.g.
server.tomcat.internal-proxies=172\\.16\\.\\d{1,3}\\.\\d{1,3}

此外,雖然我們的tomcat被nginx反向代理了,但仍可訪問到其80端口。為此可在application.properties中增加一行:

server.address=127.0.0.1

這樣一來其80端口就只能被本機(jī)訪問了,其它機(jī)器訪問不到。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容