1. 程式人生 > 其它 >關於 nginx配置 反向代理/負載均衡

關於 nginx配置 反向代理/負載均衡

1,Nginx是一款輕量級Web 伺服器/反向代理伺服器及電子郵件(IMAP/POP3)代理伺服器,在BSD-like 協議下發行。其特點是佔有記憶體少,併發能力強,事實上nginx的併發能力在同類型的網頁伺服器中表現較好。

2,Nginx作為負載均衡服務:Nginx 既可以在內部直接支援 Rails 和 PHP 程式對外進行服務,也可以支援作為 HTTP代理服務對外進行服務。

先說說什麼是正向代理,什麼是反向代理

正向代理:從原始伺服器取得內容,客戶端向代理髮送一個請求並指定目標(原始伺服器),然後代理向原始伺服器轉交請求並將獲得的內容返回給客戶端。客戶端才能使用正向代理。

        場景
:為在防火牆內的區域網客戶端提供訪問Internet的途徑   反向代理:反向代理伺服器位於使用者與目標伺服器之間,但是對於使用者而言,反向代理伺服器就相當於目標伺服器,即使用者直接訪問反向代理伺服器就可以獲得目標伺服器的資源。                   同時,使用者不需要知道目標伺服器的地址,也無須在使用者端作任何設定。        場景:反向代理伺服器通常可用來作為Web加速,即使用反向代理作為Web伺服器的前置機來降低網路和伺服器的負載,提高訪問效率。         

nginx實操篇:(在前後端分離開發時配置)

在後端的yml檔案或properties檔案裡

server.context-path=/demo-service
server.port=8088

在web前端的config.js 

Constant = {
    gatewayURL: "/demo-service",
    loginURL: "/demo-web/pages/login.html",
    uploadUrl: "/demo-service",
    ......
}

注:

IDEA啟動tomcat時,預設訪問路徑為:這裡要將登陸頁面的埠和 nginx裡的 server埠保持一致:

nginx裡新增的配置:

events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  300;
    gzip  on;
	
	
	upstream demo-web{
		server localhost:8080;
		ip_hash;
	}

	upstream demo-service{
		server localhost:8094;
		ip_hash;
	}
	
	
    server {
        listen       8081
; server_name localhost; charset utf-8; location / { add_header Cache-Control no-cache; add_header Pragma no-cache; add_header Expires 0; } location /demo-service { proxy_pass http://demo-service/demo-service; } location /demo-web { add_header Cache-Control no-cache; add_header Pragma no-cache; add_header Expires 0; proxy_pass http://demo-web/demo-web; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }