nginx可以使用 map模块来实现user_agent的匹配规则,根据不同的user_agent设置不同的变量或执行不同的操作。以下是一些常用的user_agent匹配规则示例:

蓝易云服务器 - nginx一些常用user_agent的匹配规则_Chrome

  1. 判断是否为移动设备
map $http_user_agent $is_mobile {
    default 0;
    ~*mobile 1;
    ~*Android 1;
    ~*iPhone 1;
    ~*iPad 1;
}

这个规则将会判断用户的user_agent中是否包含"mobile"、"Android"、"iPhone"或"iPad"等关键词,若包含,则将$is_mobile变量设为1,否则设为0。

  1. 拒绝某些特定的user_agent
if ($http_user_agent ~* (Baiduspider|Googlebot|bingbot)) {
    return 403;
}

这个规则将会拒绝来自百度、谷歌和必应的爬虫访问,直接返回403禁止访问状态码。

  1. 设置变量根据user_agent进行条件判断
map $http_user_agent $browser {
    default "Unknown";
    ~*MSIE "Internet Explorer";
    ~*Firefox "Mozilla Firefox";
    ~*Chrome "Google Chrome";
    ~*Safari "Apple Safari";
}

这个规则将会根据user_agent的不同设置$browser变量,用于后续的操作。

  1. 根据user_agent重定向到不同的URL
if ($http_user_agent ~* (Android|iPhone|iPad)) {
    rewrite ^/$ /mobile/ permanent;
}

这个规则将会根据user_agent中是否包含"Android"、"iPhone"或"iPad"等关键词,将根目录的访问重定向到/mobile/目录下。

需要注意的是,使用if指令可能会导致性能下降,建议尽量使用map模块进行user_agent的匹配。在编写规则时,应该确保匹配规则的准确性,以免误判或产生意外的结果。