1. 目的
- 通過nginx實(shí)現(xiàn)代理,前端HTML5只需要對接一個(gè)http端口,即可與后臺多個(gè)二級http服務(wù)進(jìn)行對接,方法是在nginx中通過不同的路徑代理不同的二級http服務(wù)。
- 靜態(tài)頁面依然使用nginx一級服務(wù)器返回。
2.Nginx服務(wù)器配置
配置nginx,訪問路徑為button1時(shí)轉(zhuǎn)發(fā)到3002端口,訪問路徑為button2時(shí)轉(zhuǎn)發(fā)到3003端口。
server {
listen 8081;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /button1 {
proxy_pass http://127.0.0.1:3002;
}
location /button2 {
proxy_pass http://127.0.0.1:3003;
}
3. ngnix靜態(tài)網(wǎng)頁編寫
ngnix中靜態(tài)文件目錄
index.html文件代碼
<form action="http://127.0.0.1:8081/button1/login.php" method="post">
<input type="submit"/>
</form>
<form action="http://127.0.0.1:8081/button2/login.php" method="post">
<input type="submit"/>
</form>
4. 二級服務(wù)器搭建
使用nodejs搭建兩個(gè)http服務(wù)器,分別監(jiān)聽3002、3003端口,代碼如下:
// 1. 加載http核心模塊
let http = require("http");
// 2. 使用http.createServer()方法創(chuàng)建一個(gè)web服務(wù)器,通過server接收
let server = http.createServer();
// 3. 服務(wù)器要做的事:提供服務(wù),發(fā)送、接收、處理請求,并發(fā)送響應(yīng)
/** server.on注冊request請求事件,客戶端請求時(shí)會自動觸發(fā)服務(wù)器的request請求事件;
回調(diào)函數(shù)對請求進(jìn)行處理,參數(shù)介紹:
req提供了請求的詳細(xì)信息。通過它可以訪問請求頭和請求的數(shù)據(jù).
res用于構(gòu)造要返回給客戶端的數(shù)據(jù)。
*/
server.on("request", function (req, res) {
// 這里的回調(diào)事件根據(jù)需要編寫即可,這里給出簡單示例
// 3.1 收到請求時(shí),打印請求的路徑
console.log(`收到客戶端的請求了,請求路徑是${req.url}`);
// 3.2 設(shè)置響應(yīng)頭中的Content-Type為plain普通文本模式,否則中文無法正常展示
res.setHeader("Content-Type", "text/plain; charset=utf-8");
let url = req.url;
// 3.3 根據(jù)不同的url展示不同內(nèi)容
if (url == "/") {
// res.write--在頁面內(nèi)寫入內(nèi)容
res.write("首頁");
} else if (url == "/login") {
res.write("登錄");
}
});
// 4.綁定端口號;
server.listen(3002, function () {
console.log("服務(wù)器啟動成功,可以通過http:127.0.0.1:3002/來進(jìn)行訪問");
});
服務(wù)器文件目錄:
在命令行運(yùn)行兩個(gè)服務(wù)
?5. 測試驗(yàn)證
瀏覽器打開顯示效果如下,該頁面使用ngnix返回html/index.html文件
?點(diǎn)擊第1個(gè)按鈕,消息轉(zhuǎn)發(fā)到3002服務(wù),點(diǎn)擊第2個(gè)按鈕消息轉(zhuǎn)發(fā)到3003服務(wù)
6.?proxy_pass設(shè)置
proxy_pass代理地址端口后無任何字符,轉(zhuǎn)發(fā)后地址:代理地址+訪問URL目錄部分
proxy_pass代理地址端口后有目錄(包括 / ),轉(zhuǎn)發(fā)后地址:代理地址+訪問URL目錄部分去除location匹配目錄(示例中的"v1"或"v1/")
代理地址為?http://127.0.0.1:3002
按鈕(http://127.0.0.1:8081/button1/login.php)URL目錄地址為:button1/test/login.php
因此以下沒有加/ 的訪問地址為:http://127.0.0.1:3002/button1/login.php
location /button1 {
proxy_pass http://127.0.0.1:3002;
}
以下加/的訪問地址為:?http://127.0.0.1:3002/login.php
location /button1 {
proxy_pass http://127.0.0.1:3002/;
}
實(shí)際測試如下:
?文章來源地址http://www.zghlxwxcb.cn/news/detail-659782.html文章來源:http://www.zghlxwxcb.cn/news/detail-659782.html
?
到了這里,關(guān)于Nginx學(xué)習(xí)1:通過訪問路徑代理不同二級http服務(wù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!