簡單配置搞定 Nginx + Tomcat + HTTPS

簡單配置搞定 Nginx + Tomcat + HTTPS

以前在網上搜索到的不少文章在描述 Nginx + Tomcat 啓用 HTTPS 支持的時候,都必須在 Nginx 和 Tomcat 兩邊同時配置 SSL 支持。但我一直在想爲何就不能按照下面的方式來配置呢?就是 Nginx 上啓用了 HTTPS,而 Nginx 和 Tomcat 之間走的倒是普通的 HTTP 鏈接。可是搜索不少沒有解決辦法,最後仍是老老實實的 Nginx 和 Tomcat 同時配置的 SSL 支持。linux

\
最近給 OSChina 買了個新的支持 *.oschina.net 泛域名的證書,而後我又開始偷懶的想爲何 Tomcat 必定要配 HTTPS 呢? 沒道理啊。而後潛心搜索終於找到了解決方案。原來倒是如此的簡單。web

最終配置的方案是瀏覽器和 Nginx 之間走的 HTTPS 通信,而 Nginx 到 Tomcat 經過 proxy_pass 走的是普通 HTTP 鏈接。apache

下面是詳細的配置(Nginx 端口 80/443,Tomcat 的端口 8080):瀏覽器

Nginx 這一側的配置沒什麼特別的:tomcat

 

 

1安全

2session

3app

4負載均衡

5webapp

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:

XHTML

 

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 中配置的一些安全策略會不起做用。

 

Nginx + Tomcat 動靜分離實現負載均衡: http://blog.jobbole.com/95376/
相關文章
相關標籤/搜索