简体   繁体   中英

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

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 Permanently" );
  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:

在此输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM