from:http://blog.csdn.net/vfush/article/details/51086274
最近做了個(gè)Web項(xiàng)目, 架構(gòu)上使用了 Nginx +tomcat 集群, 且全站HTTPS,用nginx 做負(fù)載,nginx和tomcat 使用內(nèi)網(wǎng)http通信,遇到http css,js靜態(tài)資源被瀏覽器攔截問題,網(wǎng)上搜索到的很多文章在描述 Nginx + Tomcat 啟用 HTTPS 支持的時(shí)候,都必須在 Nginx 和 Tomcat 兩邊同時(shí)配置 SSL 支持,今天做個(gè)總結(jié)。
遇到問題
- nginx強(qiáng)制使用https訪問(http跳轉(zhuǎn)到https)
- http的js,css 等靜態(tài)資源被瀏覽器攔截(http不被信任)
最后的解決方案
首先解決第一個(gè)問題全站https
參考
三種方式,跟大家共享一下
nginx的rewrite方法
server { listen 192.168.1.111:80; server_name test.com; rewrite ^(.*)$ https://$host$1 permanent; }
nginx的497狀態(tài)碼,我選擇了這種方式
server { listen 192.168.1.11:443; #ssl端口 listen 192.168.1.11:80; #用戶習(xí)慣用http訪問,加上80,后面通過497狀態(tài)碼讓它自動跳到443端口 server_name test.com; #為一個(gè)server{......}開啟ssl支持 ssl on; #指定PEM格式的證書文件 ssl_certificate /etc/nginx/test.pem; #指定PEM格式的私鑰文件 ssl_certificate_key /etc/nginx/test.key; #讓http請求重定向到https請求 error_page 497 https://$host$uri?$args; }
index.html刷新網(wǎng)頁
<html> <meta http-equiv="refresh" content="0;url=https://test.com/"> </html>
當(dāng)http訪問到index.html時(shí)候自動跳轉(zhuǎn)到https
接下來解決第二個(gè)問題
如果tomcat 和nginx 雙方?jīng)]有配置X-Forwarded-Proto tomcat就不能正確區(qū)分實(shí)際用戶是http 還是https,導(dǎo)致tomcat 里配置的靜態(tài)資源被認(rèn)為是http而被瀏覽器攔截,request.getScheme()總是 http,而不是實(shí)際的http或https
分別配置一下 Nginx 和 Tomcat ,果然好了。
配置 Nginx 的轉(zhuǎn)發(fā)選項(xiàng):
proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme;
配置Tomcat server.xml 的 Engine 模塊下配置一個(gè) Valve:
<Valve className="org.apache.catalina.valves.RemoteIpValve" remoteIpHeader="X-Forwarded-For" protocolHeader="X-Forwarded-Proto" protocolHeaderHttpsValue="https"/>
非80端口配置
Nginx增加以下配置
proxy_set_header Host $host:$server_port; 非80端口 ,用80端口時(shí) 不需要$server_port
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
Tomcat server.xml配置
<Engine name="Catalina" defaultHost="localhost">
<Valve className="org.apache.catalina.valves.RemoteIpValve"
remoteIpHeader="X-Forwarded-For"
protocolHeader="X-Forwarded-Proto"
protocolHeaderHttpsValue="https" httpsServerPort="7001"/> 非80端口時(shí),必須增加httpsServerPort配置,不然request.getServerPort()方法返回 443.
</Engine>
關(guān)于 RemoteIpValve,可以閱讀下 doc
http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/valves/RemoteIpValve.html