nginx 如何實現(xiàn)if嵌套的方法示例
nginx 不支持 if 嵌套,也不允許在 if 中使用邏輯判斷,會報如下錯誤:
nginx: [emerg] "if" directive is not allowed
當(dāng)業(yè)務(wù)需要多個條件判斷時,可以借助中間變量來實現(xiàn)
如:我們的網(wǎng)站在 pc 端有多個子域名, 而移動端只有一個域名,對應(yīng)關(guān)系如下:
- www.test.com --> m.test.com
- sub1.test.com --> m.test.com/sub1
- sub2.test.com --> m.test.com/sub2
- sub3.test.com --> m.test.com/sub3
要實現(xiàn)的效果:在移動端訪問 pc 域名時 301 跳轉(zhuǎn)到對應(yīng)的移動端域名
nginx 的重寫規(guī)則如下:
# 是否為移動端
set $mobile 0;
if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
set $mobile 1;
}
# 獲取子域名
set $prefix 1;
if ($host ~* "sub1.test.com") {
set $prefix 2;
}
if ($host ~* "sub2.test.com") {
set $prefix 3;
}
if ($host ~* "sub3.test.com") {
set $prefix 4;
}
set $sign "${mobile}${prefix}";
if ($sign = 11) {
rewrite ^(.*) http://m.test.com$1 permanent;
}
if ($sign = 12) {
rewrite ^(.*) http://m.test.com/sub1$1 permanent;
}
if ($sign = 13) {
rewrite ^(.*) http://m.test.com/sub2$1 permanent;
}
if ($sign = 14) {
rewrite ^(.*) http://m.test.com/sub3$1 permanent;
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信