首页 > 解决方案 > .htaccess 规则将爬虫重定向到另一个文件夹

问题描述

我有一个单页应用程序(react、react-router),我正在尝试将搜索和共享机器人/爬虫重定向到具有应用程序静态快照的不同文件夹。我有一个 .htaccess 设置,它大部分都在工作,但缺少一些东西。

我拥有的 .htaccess 是

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.+)$  [NC]
RewriteRule ^(.*)$ https://%1/$1 [L,R=301]

# For crawlers show snapshots
RewriteCond %{HTTP_USER_AGENT} googlebot|bingbot|yandex|baiduspider|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|quora\ link\ preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator [NC,OR]
RewriteCond %{QUERY_STRING} _escaped_fragment_
RewriteCond %{REQUEST_URI} !^/(snap) [NC]
# Proxy the request
RewriteRule ^(?!.*?(\.js|\.css|\.xml|\.less|\.png|\.jpg|\.jpeg|\.gif|\.pdf|\.doc|\.txt|\.ico|\.rss|\.zip|\.mp3|\.rar|\.exe|\.wmv|\.doc|\.avi|\.ppt|\.mpg|\.mpeg|\.tif|\.wav|\.mov|\.psd|\.ai|\.xls|\.mp4|\.m4a|\.swf|\.dat|\.dmg|\.iso|\.flv|\.m4v|\.torrent|\.ttf|\.woff))(.*) /snap/$2/ [R=301,L]

# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# If the requested pattern is file and file doesn't exist, send 404
RewriteCond %{REQUEST_URI} ^(\/[a-z_\-\s0-9\.]+)+\.[a-zA-Z]{2,4}$
RewriteRule ^ - [L,R=404]

# otherwise use history router
RewriteRule ^ /index.html [L]
</IfModule>

编辑:我将 .htaccess 的爬虫部分向上移动,现在它可以正确处理domain.com -> domain.com/snap/场景,但我不知道如何让它处理不存在的路线。

标签: apache.htaccessredirectmod-rewrite

解决方案


要将您的 uri 重定向404到正确的目的地,您可以使用以下规则。把它放在你的www to non-www重定向规则块下面,并确保在测试之前清除你的浏览器缓存:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_USER_AGENT} googlebot|bingbot|yandex|baiduspider|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|quora\ link\ preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator [NC,OR]
RewriteCond %{QUERY_STRING} _escaped_fragment_
RewriteCond %{REQUEST_URI} !^/(snap) [NC]
# Proxy the request
RewriteRule ^(?!.*?(\.js|\.css|\.xml|\.less|\.png|\.jpg|\.jpeg|\.gif|\.pdf|\.doc|\.txt|\.ico|\.rss|\.zip|\.mp3|\.rar|\.exe|\.wmv|\.doc|\.avi|\.ppt|\.mpg|\.mpeg|\.tif|\.wav|\.mov|\.psd|\.ai|\.xls|\.mp4|\.m4a|\.swf|\.dat|\.dmg|\.iso|\.flv|\.m4v|\.torrent|\.ttf|\.woff))(.*) /snap/404.html [R=301,L]

推荐阅读