菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
0
0

nginx 如何实现 if 嵌套

原创
05/13 14:22
阅读数 348

nginx 不支持 if 嵌套,也不允许在 if 中使用逻辑判断,会报如下错误:

nginx: [emerg] "if" directive is not allowed 

当业务需要多个条件判断时,可以借助中间变量来实现

如:我们的网站在 pc 端有多个子域名,而移动端只有一个域名,对应关系如下:

  • 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

要实现的效果:在移动端访问 pc 域名时 301 跳转到对应的移动端域名

nginx 的重写规则如下:

# 是否为移动端
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;
}

发表评论

0/200
0 点赞
0 评论
收藏
为你推荐 换一批