如何通过.htaccess仅向桌面用户返回404错误?
解决方案:指定URL的访问限制.htaccess配置
正确的.htaccess代码
RewriteEngine On # 针对example.com/loreupsum路径,拒绝桌面用户访问 RewriteCond %{REQUEST_URI} ^/loreupsum/?$ [NC] # 排除移动设备User-Agent RewriteCond %{HTTP_USER_AGENT} !(android|iphone|ipad|ipod|blackberry|windows phone) [NC] # 排除常见爬虫User-Agent RewriteCond %{HTTP_USER_AGENT} !(googlebot|bingbot|slurp|duckduckbot|baiduspider|yandexbot) [NC] # 符合以上条件(桌面用户)则返回404 RewriteRule ^ - [R=404,L]
代码说明
RewriteEngine On:启用mod_rewrite模块,是URL重写功能的基础前提%{REQUEST_URI} ^/loreupsum/?$ [NC]:精准匹配请求路径为/loreupsum或/loreupsum/的访问,[NC]表示规则不区分大小写- 第二个
RewriteCond:过滤掉包含移动设备关键词的请求头,确保移动用户能正常访问目标页面 - 第三个
RewriteCond:放行常见搜索引擎爬虫的请求,保证页面能被正常抓取收录 RewriteRule ^ - [R=404,L]:当以上所有条件同时满足时,直接返回404错误,[L]表示终止后续规则执行,避免冲突
测试验证方法
- 通过浏览器开发者工具修改User-Agent:
- 设置为桌面浏览器标识(如
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36),访问目标路径应显示404页面 - 设置为移动设备标识(如
Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15),应能正常加载页面内容 - 设置为爬虫标识(如
Mozilla/5.0 (compatible; Googlebot/2.1)),应能正常访问页面
- 设置为桌面浏览器标识(如
内容的提问来源于stack exchange,提问作者Vishal Gupta
相关产品推荐
相关产品推荐

