Example of how nginx implements if nesting


Nginx does not support if nesting and does not allow logical judgment in if. The following error will be reported:

nginx: [emerg] “if” directive is not allowed

When the business needs more than one condition judgment, it can be realized with the help of intermediate variables

For example, our website has multiple sub domain names on the PC side, while the mobile terminal has only 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/sub3

To achieve the effect: 301 jumps to the corresponding mobile domain name when the mobile terminal accesses the PC domain name

The rewriting rules of nginx are as follows:

#Is it a mobile terminal
set $mobile 0;
if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
  set $mobile 1;

#Get subdomain name
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;

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]