Nginx負載均衡反向代理伺服器

名無發表於2021-07-31

1、第一步先在IIS中建立多個網站,分別用不同的埠號。這裡建立兩個網站埠號分別8084、8085,在Nginx配置中會用到。測試兩個網站能正常訪問。

2、配置Nginx

1)增加負載均衡請求列表

upstream ytest {
server 127.0.0.1:8084 weight=1;
server 127.0.0.1:8085 weight=2;
}

2)配置Nginx對外請求地址

server {
listen 80;
server_name www.hellonginx.com ; #對外提供訪問地址
location / {
root html;
index index.html index.htm;
proxy_pass http://ytest; #負載均衡列表
}
}

到這裡我們的Nginx就配好了,是不是想看到效果,別急這裡還沒有完,因為我們增加了一個域名。所以還需要在hosts中增加域名配置。

3、域名配置

hosts地址:C:\Windows\System32\drivers\etc,開啟hosts檔案,在尾部增加:127.0.0.1 www.hellonginx.com 

最後開啟瀏覽器,在位址列中輸入:www.hellonginx.com,但是這裡開啟的網址輸出的內容都一樣,不知道開啟是哪個網站。

這裡就需要再回到網站修改一下程式碼,這裡我建立的是asp.net mvc網站,直接上乾貨:

Controller中修改Index ,程式碼:

public ActionResult Index()
{
var serverName = "伺服器名稱:" + Server.MachineName;
var ip = "伺服器IP地址:" + Request.ServerVariables["LOCAL_ADDR"];
var port = Request.ServerVariables["SERVER_PORT"];
var portStr = "HTTP訪問埠:" + Request.ServerVariables["SERVER_PORT"];
var message = "hello nginx";
if (port == "8084") message = "good morning,Sir";
ViewBag.serverName = serverName;
ViewBag.ip = ip;
ViewBag.portStr = portStr;
ViewBag.message = message;
return View();
}

前端View:

<div class="jumbotron">
<p>@ViewBag.serverName</p>
<p>@ViewBag.ip</p>
<p>@ViewBag.portStr</p>
<p>@ViewBag.message</p>
</div>

再次生成釋出,看效果如下圖:

 

相關文章