开发者

PHP5: how to Check & Set pre-defined canonical URL as header location via redirect 301?

开发者 https://www.devze.com 2023-02-21 12:16 出处:网络
Im stuck with a common mistake of duplicate content that I want to solve: A hyperlink in the browser shows: http://website.org/nl/amsterdam

Im stuck with a common mistake of duplicate content that I want to solve:

A hyperlink in the browser shows: http://website.org/nl/amsterdam

Now, thats not the canonical URL and I would wish to have the webpage redirect to its known canonical url (on the condition that the current page is not already the canonical page)

<?php $canonical = "http://website.org/nl/amsterdam-grass-is-greener;

  header("HTTP/1.1 301 Moved Permanentl开发者_如何学运维y" );
  header("Status: 301 Moved Permanently" );
  header("Location: " . $canonical);  // shows below picture, while url looks good

  exit(0);

<html><head><link rel="canonical" href="<?=$canonical?></head>...</html>

Main Question: How to get this to work? Currently the non canonical url seems to wanna direct to the canonical url (tested via HEAD info) but once it arrives there PHP gets stuck and shows:

PHP5: how to Check & Set pre-defined canonical URL as header location via redirect 301?

Minor Question: Does this idea sound good to you? Since search engines do not use canonical so strictly and only use it as a hint, often saving the wrong, non canonical url. Does the above rule make it more strong via the 301 redirect for search engines to save the good versions in search results? Does this also solve my duplicate content url problem?


Try:

if(isset($canonical) && ('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] != $canonical)) {
  header ('HTTP/1.1 301 Moved Permanently');
  header('Location: ' . $canonical);
  exit();
}

To answer your more general question, this is not a tenable solution (unless your site is very small) because it requires you to hard code the canonical URL of every page. As near as possible, you should aim to create a URL structure that only has one URI per resource. However, it does solve the immediate problem of search engines perceiving duplicate content.

Edit: Thanks Gumbo.


It seems canonical tries to redirect too.
You have to use some HTTP sniffer to see what ACTUALLY happens when you press some button. Get yourself one like LiveHTTPHeaders Firefox add-on of whatever else and see what redirects being made.

0

精彩评论

暂无评论...
验证码 换一张
取 消