让nginx为PC和移动设备加载不同的位置

让nginx为PC和移动设备加载不同的位置,nginx,Nginx,我想让PC和移动设备加载不同索引的文件 因此,在nginx主“位置”之前,我尝试创建一个“如果”,如下所示: # 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|op

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

因此,在nginx主“位置”之前,我尝试创建一个“如果”,如下所示:

# 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 ;
    }    
}
if ($http_user_agent ~* android) {
    rewrite ^ /mobile/$request_uri last; # internal rewrite
}

location /mobile {
}

但是,我得到了“nginx:[emerg]“location”指令在这里是不允许的”。由于在if中不允许使用位置,为了实现针对不同条件提供不同文件的nginx,有哪些方向?

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

在您的特定情况下,请尝试以下方法:

# 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 ;
    }    
}
if ($http_user_agent ~* android) {
    rewrite ^ /mobile/$request_uri last; # internal rewrite
}

location /mobile {
}

请注意,我还没有验证您的正则表达式。我相信你可以根据你的需要调整它。

应该是
重写。*/mobile/$request\u uri last?@calfzhou感谢您发现了这个小错误。您的解决方案会起作用,但请考虑使用<代码>重写^ /移动/$Restestuuri;代码>取而代之。简单的
^
模式要比
*
便宜得多。