nginx 如何实现 if 嵌套

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;
}

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

php
本作品采用《CC 协议》,转载必须注明作者和本文链接
it书童
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!