简单配置搞定 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/
相关文章
相关标签/搜索