【问题标题】:Make nginx load different locations for PC and mobile devices让 nginx 为 PC 和移动设备加载不同的位置
【发布时间】:2013-06-08 21:28:13
【问题描述】:

我想让 PC 和移动设备加载不同的索引文件。

所以,在 nginx 主“位置”之前,我尝试创建一个这样的“if”:

# START MOBILE
if ($http_user_agent ~* "(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino") {
    location / {
        try_files /my/dir/here/index-mobile.html $uri $uri/ /index.php ;
    }    
}

但是,我得到“nginx:[emerg]“位置”指令在此处不允许”。由于 if 中不允许定位,为了实现 nginx 为不同条件提供不同文件的方向是什么?

【问题讨论】:

    标签: nginx


    【解决方案1】:

    问题如上所示:if 中不允许使用 location 指令。在if 指令中实际上只有几件事是安全的,例如rewritereturn。有关更多详细信息,请参阅文档information。文档没有提到的是,在某些条件下set 也可以安全使用。

    在您的具体情况下,请尝试以下操作:

    if ($http_user_agent ~* android) {
        rewrite ^ /mobile/$request_uri last; # internal rewrite
    }
    
    location /mobile {
    }
    

    请注意,我尚未验证您的正则表达式。我相信您可以根据自己的需要进行调整。

    【讨论】:

    • 应该是rewrite .* /mobile/$request_uri last;
    • @calfzhou 感谢您发现这个小错误。您的解决方案可行,但请考虑改用rewrite ^ /mobile/$request_uri last;。简单的^ 模式比.* 要便宜得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多