How does nginx implement if nested method examples
- 2020-05-17 07:51:19
- OfStack
nginx does not support nesting of if, nor does it allow the use of logical judgments in if. The following error is reported:
[
nginx: [emerg] "if" directive is not allowed
When the business needs more than one conditional judgment, it can be implemented with intermediate variables
For example, our website has several sub-domains in pc terminal, while the mobile terminal only has one domain name. The corresponding relationship is as follows:
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/sub3To achieve the effect: when the mobile terminal access pc domain name 301 jump to the corresponding mobile terminal domain name
The rewriting rules for nginx are as follows:
# Whether it is a mobile terminal
set $mobile 0;
if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
set $mobile 1;
}
# Get subdomain
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;
}