User-Agent是一个HTTP请求头字段,用于标识发起请求的用户代理(例如浏览器、爬虫、自动化程序等)。它包含了一些关于用户代理的信息,例如操作系统、浏览器名称和版本等。
User-Agent的格式通常为:
User-Agent: <user_agent_string>
例如:

下面是一些常见的 User-Agent 示例:
1. Chrome 浏览器(Windows)
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
2. Safari 浏览器(Mac)
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15
3. Firefox 浏览器(Windows)
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0
4. Edge 浏览器(Windows)
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59
5. iPhone 的 Safari 浏览器
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Mobile/15E148 Safari/604.1
通过解析 User-Agent 字段,可以获取有关用户代理的信息,例如操作系统、浏览器类型和版本等,这对于服务器端应用程序来说是有用的,可以根据用户代理的不同来提供定制化的内容或功能。
下面示例通过过滤 User-Agent 阻止常见爬虫访问服务器资源,nginx.conf 配置如下:
worker_processes 1;
debug_points abort;
events {
worker_connections 1024;
#accept_mutex on;
}
http {
include mime.types;
default_type application/octet-stream;
include server_demo.conf;
log_format main '$pid - $connection - $request_uri - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
sendfile on;
keepalive_timeout 65;
server {
listen 8080;
server_name localhost;
# 关键配置
# 使用 user_agent 阻止百度、360、google 和必应搜索引擎抓取
# 如果 user_agent 字符串包含 Baiduspider、360spider、Googlebot 和 bingbot 字符串
# 中任何一个,则直接返回 404 状态
if ($http_user_agent ~* (Baiduspider|360spider|Googlebot|bingbot) ) {
return 404;
}
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
挺好的
谢谢支持