原文網(wǎng)址:Nginx系列--轉(zhuǎn)發(fā)請(qǐng)求的方法_IT利刃出鞘的博客-CSDN博客
簡(jiǎn)介
說(shuō)明
本文介紹Nginx轉(zhuǎn)發(fā)請(qǐng)求的方法。
分享Java技術(shù)星球(自學(xué)精靈):https://learn.skyofit.com/
需求
用戶(hù)訪問(wèn)aaa.com/bbb時(shí),實(shí)際訪問(wèn)的是bbb123.com。
方案1:return
方法
server {
? ? listen? ? ? 8080;
? ? server_name? aaa.com;
? ? location /bbb {
? ? ? ? return 302 https://bbb123.com$request_uri;
? ? }
}
說(shuō)明
瀏覽器會(huì)直接跳轉(zhuǎn)到https://bbb123.com,相當(dāng)于直接location.href = ‘https://bbb123.com’ 。
方案2:rewrite
方法
法1:正則匹配所有的URI再去掉開(kāi)頭第一個(gè)/(反斜線)。
server {
? ? listen? ? ? 80;
? ? server_name? aaa.com;
? ? rewrite ^/(.*)$ https://bbb123.com/$1 permanent;
}
法2:?$request_uri變量匹配所有的URI。
server {
? ? listen? ? ? 80;
? ? server_name? aaa.com;
? ? rewrite ^ https://bbb123.com$request_uri? permanent;
}
法3:與if結(jié)合
server {
? ? listen? ? ? 80;
? ? server_name? aaa.com abc.com;
? ? if ($host = 'aaa.com' ) {
? ? ? ? rewrite ^/(.*)$ https://bbb123.com/$1 permanent;
? ? }
}
說(shuō)明
瀏覽器會(huì)直接跳轉(zhuǎn)到https://bbb123.com,相當(dāng)于直接location.href = ‘https://bbb123.com’ 。
方案3:proxy_pass
方法
server {
? ? listen? ? ? 80;
? ? server_name? aaa.com;
? ? location /aaa/ {
? ? ? ? proxy_pass https://bbb123.com;
? ? }
}
說(shuō)明
瀏覽器顯示的仍然是aaa.com/aaa,用戶(hù)是不知道https://bbb123.com的存在的。
聯(lián)合使用
上邊三者是可以聯(lián)合使用的,例如:
例1:rewrite帶break
server {
? ? listen? ? ? 80;
? ? server_name? localhost;
? ? location /abc {
? ? ? ? # 只保留/abc/后面的路徑
? ? ? ? rewrite ^/abc/(.*)$ /proxy/$1 break;
? ? ? ? # 改寫(xiě)完之后, 再進(jìn)行代理; 最終結(jié)果: http://www.proxy_pass.com/proxy/$1
? ? ? ? proxy_pass http://www.proxy_pass.com;
? ? }
? ? location / {
? ? ? ? root? /usr/share/nginx/html;
? ? ? ? index? index.html index.htm index.php;
? ? }
}
訪問(wèn):localhost/abc/aaa
實(shí)際訪問(wèn):http://www.proxy_pass.com/abc/aaa(用戶(hù)無(wú)感知)
例2:rewrite不帶break
server {
? ? listen? ? ? 80;
? ? server_name? localhost;
? ? location /abc {
? ? ? ? # 只保留/abc/后面的路徑
? ? ? ? rewrite ^/abc/(.*)$ /proxy/$1;
? ? ? ? # 改寫(xiě)完之后, 再進(jìn)行代理; 最終結(jié)果: http://www.proxy_pass.com/proxy/$1
? ? ? ? proxy_pass http://www.proxy_pass.com;
? ? }
? ? location / {
? ? ? ? root? /usr/share/nginx/html;
? ? ? ? index? index.html index.htm index.php;
? ? }
}
訪問(wèn):localhost/abc/aaa
實(shí)際訪問(wèn):/usr/share/nginx/html/index.html(用戶(hù)無(wú)感知)