m.test.comsub1.test.com-->m.test.com/sub1sub2.test.com-->m.test.com/sub2sub3.test.c"/> m.test.comsub1.test.com-->m.test.com/sub1sub2.test.com-->m.test.com/sub2sub3.test.c">
首页 > 运维 > nginx > 正文

nginx怎么实现if嵌套

PHPz
发布: 2023-05-13 12:01:15
转载
2444 人浏览过

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;
}
登录后复制

以上是nginx怎么实现if嵌套的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:yisu.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!