from:http://blog.csdn.net/vfush/article/details/51086274
最近做了個Web項目, 架構上使用了 Nginx +tomcat 集群, 且全站HTTPS,用nginx 做負載,nginx和tomcat 使用內網http通信,遇到http css,js靜態資源被瀏覽器攔截問題,網上搜索到的很多文章在描述 Nginx + Tomcat 啟用 HTTPS 支持的時候,都必須在 Nginx 和 Tomcat 兩邊同時配置 SSL 支持,今天做個總結。
遇到問題
- nginx強制使用https訪問(http跳轉到https)
- http的js,css 等靜態資源被瀏覽器攔截(http不被信任)
最后的解決方案
首先解決第一個問題全站https
參考
三種方式,跟大家共享一下
nginx的rewrite方法
server { listen 192.168.1.111:80; server_name test.com; rewrite ^(.*)$ https://$host$1 permanent; }
nginx的497狀態碼,我選擇了這種方式
server { listen 192.168.1.11:443; #ssl端口 listen 192.168.1.11:80; #用戶習慣用http訪問,加上80,后面通過497狀態碼讓它自動跳到443端口 server_name test.com; #為一個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刷新網頁
<html> <meta http-equiv="refresh" content="0;url=https://test.com/"> </html>
當http訪問到index.html時候自動跳轉到https
接下來解決第二個問題
如果tomcat 和nginx 雙方沒有配置X-Forwarded-Proto tomcat就不能正確區分實際用戶是http 還是https,導致tomcat 里配置的靜態資源被認為是http而被瀏覽器攔截,request.getScheme()總是 http,而不是實際的http或https
分別配置一下 Nginx 和 Tomcat ,果然好了。
配置 Nginx 的轉發選項:
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 模塊下配置一個 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端口時 不需要$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端口時,必須增加httpsServerPort配置,不然request.getServerPort()方法返回 443.
</Engine>
關于 RemoteIpValve,可以閱讀下 doc
http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/valves/RemoteIpValve.html