nginx配置端口轉(zhuǎn)發(fā)SSL
下面例子介紹配置nginx實現(xiàn)SSL端口到非SSL端口,以及非SSL端口到SSL端口的轉(zhuǎn)發(fā)功能。
- 創(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"}
- 安裝nginx
下載:nginx-1.16.0
./configure --prefix=/path/to/nginx --with-stream --with-stream_ssl_module
- 配置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ā)功能是正常的。
- 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"}
- 非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"}