之前在網上搜索到的很多文章在描述 Nginx + Tomcat 啓用 HTTPS 支持的時候,都必須在 Nginx 和 Tomcat 兩邊同時配置 SSL 支持。但我一直在想爲什麼就不能按照下面的方式來配置呢?就是 Nginx 上啓用了 HTTPS,而 Nginx 和 Tomcat 之間走的卻是普通的 HTTP 連接。但是搜索很多沒有解決辦法,最後還是老老實實的 Nginx 和 Tomcat 同時配置的 SSL 支持。
最近給 OSChina 買了個新的支持 *.oschina.net 泛域名的證書,然後我又開始偷懶的想爲什麼 Tomcat 一定要配 HTTPS 呢? 沒道理啊。然後潛心搜索終於找到了解決方案。原來卻是如此的簡單。
最終配置的方案是瀏覽器和 Nginx 之間走的 HTTPS 通訊,而 Nginx 到 Tomcat 通過 proxy_pass 走的是普通 HTTP 連接。
下面是詳細的配置(Nginx 端口 80/443,Tomcat 的端口 8080):
Nginx 這一側的配置沒什麼特別的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
upstream
tomcat { server
127.0.0.1:8080 fail_timeout=0; } #
HTTPS server server
{ listen
443 ssl; server_name
localhost; ssl_certificate
/Users/winterlau/Desktop/SSL/oschina .bundle.crt; ssl_certificate_key
/Users/winterlau/Desktop/SSL/oschina .key; ssl_session_cache
shared:SSL:1m; ssl_session_timeout
5m; ssl_ciphers
HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers
on; location
/ { proxy_set_header
X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header
Host $http_host; proxy_set_header
X-Forwarded-Proto https; proxy_redirect
off; proxy_connect_timeout
240; proxy_send_timeout
240; proxy_read_timeout
240; #
note, there is not SSL here! plain HTTP is used proxy_pass
http: //tomcat ; } } |
其中最爲關鍵的就是 ssl_certificate 和 ssl_certificate_key 這兩項配置,其他的按正常配置。不過多了一個 proxy_set_header X-Forwarded-Proto https; 配置。
最主要的配置來自 Tomcat,下面是我測試環境中的完整 server.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<? xml
version = '1.0'
encoding = 'utf-8' ?> < Server
port = "8005"
shutdown = "SHUTDOWN" > < Service
name = "Catalina" > < Connector
port = "8080"
protocol = "HTTP/1.1" connectionTimeout = "20000" redirectPort = "443" proxyPort = "443" /> < Engine
name = "Catalina"
defaultHost = "localhost" > < Host
name = "localhost"
appBase = "webapps" unpackWARs = "true"
autoDeploy = "true" > < Valve
className = "org.apache.catalina.valves.RemoteIpValve" remoteIpHeader = "x-forwarded-for" remoteIpProxiesHeader = "x-forwarded-by" protocolHeader = "x-forwarded-proto" /> < Context
path = ""
docBase = "/oschina/webapp"
reloadable = "false" /> </ Host > </ Engine > </ Service > </ Server > |
上述的配置中沒有什麼特別的,但是特別特別注意的是必須有 proxyPort="443",這是整篇文章的關鍵,當然 redirectPort 也必須是 443。同時 <Value> 節點的配置也非常重要,否則你在 Tomcat 中的應用在讀取 getScheme() 方法以及在 web.xml 中配置的一些安全策略會不起作用。
怎麼樣,簡單到一塌糊塗吧!!!