nginx代理web服務(http、https)和tcp服務

Nginx (engine x) 是一個高效能的HTTP和反向代理web伺服器,也可以代理tcp伺服器,實現負載、主備功能。

下面分別是http、https和tcp伺服器的配置。

1。nginx代理http

upstream tomcatserver{server ip:8080 max_fails=2 fail_timeout=30s;server ip:8090 max_fails=2 fail_timeout=30s backup;}location /usercenter {proxy_connect_timeout 1;proxy_read_timeout 1;proxy_send_timeout 1;proxy_next_upstream error timeout http_502 http_503 http_504;proxy_pass http://tomcatserver/usercenter;}

ip:8080主機

ip:8090備機

引數解釋

backup 引數是作為備機使用,當主機掛掉了就會頂上。

max_fails引數的理解:max_fails預設為1,fail_timeout預設為10秒,也就是說,十秒內超過一次故障,標記裝置不可用。

proxy_connect_timeout 引數是連線的超時時間。 設定成1,表示是1秒後超時會連線到另外一臺伺服器。

proxy_read_timeout 引數是接收資料超時時間, 設定成1, 如果連續的1s內沒有收到1個位元組, 連線關閉,預設60s。

proxy_send_timeout 引數是傳送資料到伺服器的超時時間, 設定成1, 如果連續的1s內沒有傳送1個位元組, 連線關閉,預設60s。

2。nginx代理tcp伺服器

nginx 1。9。0以上版本可以支援tcp服務代理

服務埠 9611

代理服務1:192。168。2。148:9611 權重5

代理服務2:192。168。2。132:9611 權重1

備機:192。168。6。130 當服務1和服務2失敗的時候會使用備機。

開啟conf/nginx。conf配置檔案,輸入如下內容。

stream {upstream backend {# hash $remote_addr consistent;server 192。168。2。148:9611 weight=5 max_fails=1 fail_timeout=30s;server 192。168。2。132:9611 weight=1;server 192。168。6。130:9610 backup;}server {listen 9611 so_keepalive=on; proxy_connect_timeout 10s; proxy_timeout 300s;proxy_pass backend;}}

3。nginx搭建https伺服器

首先https需要證書,利用openssl可以生成證書請求或生成證書。在linux終端使用openssl命令即可生成。

1、生成RSA金鑰的方法

openssl genrsa -des3 -out privkey。pem 2048

這個命令會生成一個2048位的金鑰,同時有一個des3方法加密的密碼,如果你不想要每次都輸入密碼,可以改成:openssl genrsa -out privkey。pem 2048建議用2048位金鑰,少於此可能會不安全或很快將不安全。

2、生成一個證書請求

openssl req -new -key privkey。pem -out cert。csr

這個命令將會生成一個證書請求,當然,用到了前面生成的金鑰privkey。pem檔案

這裡將生成一個新的檔案cert。csr,即一個證書請求檔案,你可以拿著這個檔案去數字證書頒發機構(即CA)申請一個數字證書。CA會給你一個新的檔案cacert。pem,那才是你的數字證書。

現在自己做測試,那麼證書的申請機構和頒發機構都是自己。就可以用下面這個命令來生成證書:

openssl req -new -x509 -key privkey。pem -out cacert。pem -days 1095

這個命令將用上面生成的金鑰privkey。pem生成一個數字證書cacert。pem

有了privkey。pem和cacert。pem檔案後就可以在做一個https伺服器。

nginx https服務配置

# HTTPS server

server { listen 443 ssl; server_name localhost; ssl_certificate cacert。pem; ssl_certificate_key privkey。pem; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { root html; index index。html index。htm; }}

測試 https://192。168。6。130:443

nginx代理web服務(http、https)和tcp服務

再補充一條,一個nginx伺服器可以同時代理多個服務。