nginx配置端口转发SSL

nginx配置端口转发SSL

下面例子介绍配置nginx实现SSL端口到非SSL端口,以及非SSL端口到SSL端口的转发功能。

  1. 创建两个REST Service

非SSL server ,监听端口18080,提供服务:

$ curl http://<yourhostname>:18080/service/hello                                             
{"hello":"http"}

SSL server,监听端口18081,提供服务:

$ curl --cacert ./tlsca.pem https://<yourhostname>:18081/service/hello
{"hello":"https"}
  1. 安装nginx

下载:nginx-1.16.0

./configure --prefix=/path/to/nginx --with-stream --with-stream_ssl_module
  1. 配置nginx

在conf/nginx.conf里面增加下面一节:

stream {
    upstream http_hello {
        server <yourhostname>:18080;
    }
    upstream https_hello {
        server <yourhostname>:18081;
    }

    # http(28080) -> http(18080)
    server {
        listen *:28080;
        proxy_pass http_hello;
    }

    # https(28081) -> https(18081)
    server {
        listen *:28081 ssl;
        proxy_pass https_hello;
        proxy_ssl  on;

        ssl_certificate     /path/to/tlsserver.pem;
        ssl_certificate_key /path/to/tlsserver.key.pem;
    }
}

这个配置里面,nginx提供两个端口服务:28080和28081,分别映射到http服务端口(18080)和https服务端口(18081),启动nginx,测试:

$ ./sbin/nginx -s reload

$ curl http://<yourhostname>:28080/service/hello
{"hello":"http"}

$ curl --cacert ./tlsca.pem https://<yourhostname>:28081/service/hello
{"hello":"https"}

可见nginx的端口转发功能是正常的。

  1. SSL端口到非SSL端口的转发

在前面第3步中,实现的是SSL端口到SSL端口,以及非SSL端口到非SSL端口的转发;很多时候我们需要SSL端口到非SSL端口的转发,也就是说我们提供的服务是非SSL的,但是出于安全的考虑这个服务并不对外发布,然后对外通过nginx提供外部访问服务,然后把客户端的SSL请求转发到内部的非SSL服务端口。
下面的例子,nginx发布SSL端口28091,然后把请求转到内部的非SSL端口18080。

stream {
    upstream http_hello {
        server <yourhostname>:18080;
    }
    upstream https_hello {
        server <yourhostname>:18081;
    }

    # https -> http
    server {
        listen *:28091 ssl;
        proxy_pass http_hello;

        ssl_certificate     /path/to/tlsserver.pem;
        ssl_certificate_key /path/to/tlsserver.key.pem;
    }
}

验证:

$ curl --cacert ./tlsca.pem https://<yourhostname>:28091/service/hello
{"hello":"http"}
  1. 非SSL端口到SSL端口的转发

这个场景是根据前面第4个场景对比出来的,但我真想不出真实是不是有这种需求。

下面的例子,nginx发布非SSL端口28090,然后把请求转到内部的SSL端口18081。

stream {
    upstream http_hello {
        server <yourhostname>:18080;
    }
    upstream https_hello {
        server <yourhostname>:18081;
    }

    # http -> https
    server {
        listen *:28090;
        proxy_pass https_hello;
        proxy_ssl  on;

        ssl_certificate     /path/to/tlsserver.pem;
        ssl_certificate_key /path/to/tlsserver.key.pem;
    }
}

测试:

$ curl http://<yourhostname>:28090/service/hello
{"hello":"https"}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容