前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >nginx 如何实现if嵌套

nginx 如何实现if嵌套

作者头像
章鱼喵
发布2019-11-27 21:15:15
1.6K0
发布2019-11-27 21:15:15
举报
文章被收录于专栏:codingcoding

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

代码语言:javascript
复制
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 的重写规则如下:

代码语言:javascript
复制
# 是否为移动端
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;
}

原文 https://www.itshutong.com/363.html

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档