【发布时间】:2021-12-02 00:26:21
【问题描述】:
我有以下多语言 URL 结构:
example.com/article123 # english
example.com/fr/article123 # french
example.com/de/article123 # german
根据浏览器语言 ($_SERVER['HTTP_ACCEPT_LANGUAGE']),会自动 302 重定向到相关语言。这有利于用户体验,因为大多数用户无需手动单击语言切换器。根据我的统计,效果不错。
问题:当使用 Ahrefs 网站审核工具时(搜索引擎爬虫、GoogleBot 等也一样),我看到 他们的爬虫被 302 重定向,因此永远不要访问法国网站。
确实,当爬虫(可能设置为英文)访问example.com/fr/article123 时,它将被重定向到example.com/article123。我想这些爬虫没有考虑 cookie,所以所有页面都是一样的。
我应该使用什么技术解决方案来避免搜索引擎机器人错误地抓取多语言网站?
TL;DR:我怎样才能根据普通用户的浏览器语言触发重定向,并且不重定向机器人(例如负责“分享”的 GoogleBot、Facebook 或 Twitter 爬虫...”显示的卡片)?
这是我用的:
function lang_redirect() {
if (isset($_COOKIE['lang_redirect'])) // already redirected in the last 24 hours, don't do it again
return;
global $lang, $requesturi;
$browserlang = getlang($_SERVER['HTTP_ACCEPT_LANGUAGE']); // fr, de, en...
$link = lang_translation_link($browserlang);
if (($browserlang != $lang) && ($link != ''))
header("Location: " . $link); // redirect now!
header("Set-Cookie: lang_redirect=1; Max-Age=86400; Path=/; HttpOnly; SameSite=Lax");
}
注意:重定向只发生一次(通过设置 cookie),因为浏览器设置为德语的访问者可能想要访问英文网站而不被重定向每次到德国网站。示例:
example.com/article123 # browser set to german
=> example.com/de/article123 # automatic redirection, setting a cookie to not redirect anymore
example.com/article123 # user returns on english website
=> no redirection here because there has already been a first redirection
【问题讨论】:
标签: php redirect cookies web-crawler multilingual