0

假设您为一家拥有相当大的电子商务网站的公司工作,该网站包含许多产品类别和子类别(有时还有子子类别)。因此,为了方便用户,有些类别具有重复的子类别和重复的内容。每当用户登陆这些重复类别之一并将其指向对 SEO 更友好的类别时,您想使用 PHP 生成 rel canonical。在这种情况下,带有重复子类别的类别是“随机的东西”,而我希望规范指向的类别是“各种东西”。所以,item_1.html - item_4.html 都在“随机东西”和“各种东西”中找到,但我希望规范指向“各种东西”。目前,这就是我所拥有的:

<?php if(is_numeric(strpos($_SERVER['REQUEST_URI'],'random-stuff/item_1.html'))) echo '<link rel="canonical" href="http://mydomain.com'.str_replace('random-stuff', 'assorted-things', $_SERVER['REQUEST_URI']).'" />'; ?>
<?php if(is_numeric(strpos($_SERVER['REQUEST_URI'],'random-stuff/item_2.html'))) echo '<link rel="canonical" href="http://mydomain.com'.str_replace('random-stuff', 'assorted-things', $_SERVER['REQUEST_URI']).'" />'; ?>
<?php if(is_numeric(strpos($_SERVER['REQUEST_URI'],'random-stuff/item_3.html'))) echo '<link rel="canonical" href="http://mydomain.com'.str_replace('random-stuff', 'assorted-things', $_SERVER['REQUEST_URI']).'" />'; ?>
<?php if(is_numeric(strpos($_SERVER['REQUEST_URI'],'random-stuff/item_4.html'))) echo '<link rel="canonical" href="http://mydomain.com'.str_replace('random-stuff', 'assorted-things', $_SERVER['REQUEST_URI']).'" />'; ?>

它有效,但它很混乱。我宁愿用一行代码检查 item-1.html - item4.html 而不是四次检查。有谁知道如何实现这一目标?

另外,请记住 item_1.html - item_4.html 不是“随机东西”中唯一的东西,它们只是与“各种东西”共享的重复类别。谢谢!!

更新:

Marty 建议使用该glob()函数循环遍历目录中的所有文件并仅回显我需要的内容。这是我提出的代码:

$dir = 'http://www.mydomain.com/random-stuff/*'; 
foreach(glob($dir) as $file) {
   if($file == 'item_1.html' || 'item_2.html' ||'item_3.html' ||'item_4.html') {
   echo '<link rel="canonical" href="http://mydomain.com'.str_replace('random-stuff', 'assorted-things', $_SERVER['REQUEST_URI']).'" />';
   }
}

这似乎仍然不起作用。谁能进一步照亮我?我从根本上误解了这里的东西吗?

4

1 回答 1

1

这是一个更好的解决方案: - 抱歉,顺便说一下,我理解你的问题是错误的 -

// First, get last portion of url
$filename = end(explode('/',$_SERVER['REQUEST_URI']));

// Check if the same filename exists in 'assorted-things' directory:
if (file_exists("../assorted-things/$filename")) {
    // If so, echo canonical
    echo '<link rel="canonical" href="http://mydomain.com/assorted-things/' . $filename . '" />';
}
于 2013-04-11T20:17:07.433 回答