nginx配置端口轉(zhuǎn)發(fā)SSL

nginx配置端口轉(zhuǎn)發(fā)SSL

下面例子介紹配置nginx實現(xiàn)SSL端口到非SSL端口,以及非SSL端口到SSL端口的轉(zhuǎn)發(fā)功能。

  1. 創(chuàng)建兩個REST Service

非SSL server ,監(jiān)聽端口18080,提供服務:

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

SSL server,監(jiān)聽端口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里面增加下面一節(jié):

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的端口轉(zhuǎn)發(fā)功能是正常的。

  1. SSL端口到非SSL端口的轉(zhuǎn)發(fā)

在前面第3步中,實現(xiàn)的是SSL端口到SSL端口,以及非SSL端口到非SSL端口的轉(zhuǎn)發(fā);很多時候我們需要SSL端口到非SSL端口的轉(zhuǎn)發(fā),也就是說我們提供的服務是非SSL的,但是出于安全的考慮這個服務并不對外發(fā)布,然后對外通過nginx提供外部訪問服務,然后把客戶端的SSL請求轉(zhuǎn)發(fā)到內(nèi)部的非SSL服務端口。
下面的例子,nginx發(fā)布SSL端口28091,然后把請求轉(zhuǎn)到內(nèi)部的非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端口的轉(zhuǎn)發(fā)

這個場景是根據(jù)前面第4個場景對比出來的,但我真想不出真實是不是有這種需求。

下面的例子,nginx發(fā)布非SSL端口28090,然后把請求轉(zhuǎn)到內(nèi)部的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"}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容