系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > server > anz > 详细页面

nginx 如何实现if嵌套的方法示例

时间:2019-12-11来源:系统城作者:电脑系统城

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 的重写规则如下:


 
  1. # 是否为移动端
  2. set $mobile 0;
  3. if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
  4. set $mobile 1;
  5. }
  6.  
  7. # 获取子域名
  8. set $prefix 1;
  9. if ($host ~* "sub1.test.com") {
  10. set $prefix 2;
  11. }
  12. if ($host ~* "sub2.test.com") {
  13. set $prefix 3;
  14. }
  15. if ($host ~* "sub3.test.com") {
  16. set $prefix 4;
  17. }
  18. set $sign "${mobile}${prefix}";
  19. if ($sign = 11) {
  20. rewrite ^(.*) http://m.test.com$1 permanent;
  21. }
  22. if ($sign = 12) {
  23. rewrite ^(.*) http://m.test.com/sub1$1 permanent;
  24. }
  25. if ($sign = 13) {
  26. rewrite ^(.*) http://m.test.com/sub2$1 permanent;
  27. }
  28. if ($sign = 14) {
  29. rewrite ^(.*) http://m.test.com/sub3$1 permanent;
  30. }
  31.  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

分享到:

相关信息

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载