19人参与 • 2025-07-20 • Mysql
nginx可以使用 map
模块来实现user_agent的匹配规则,根据不同的user_agent设置不同的变量或执行不同的操作。
以下是一些常用的user_agent匹配规则示例:
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。
if ($http_user_agent ~* (baiduspider|googlebot|bingbot)) { return 403; }
这个规则将会拒绝来自百度、谷歌和必应的爬虫访问,直接返回403禁止访问状态码。
map $http_user_agent $browser { default "unknown"; ~*msie "internet explorer"; ~*firefox "mozilla firefox"; ~*chrome "google chrome"; ~*safari "apple safari"; }
这个规则将会根据user_agent的不同设置$browser变量,用于后续的操作。
if ($http_user_agent ~* (android|iphone|ipad)) { rewrite ^/$ /mobile/ permanent; }
这个规则将会根据user_agent中是否包含"android"、"iphone"或"ipad"等关键词,将根目录的访问重定向到/mobile/目录下。
需要注意的是:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论