問題描述
項(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ī)器訪問不到。