What are some best practices for handling URL routing in PHP applications to avoid duplicate content issues?
Duplicate content issues can arise in PHP applications when multiple URLs lead to the same content, which can negatively impact SEO. To avoid this, it's important to set up proper URL routing to ensure that only one canonical URL is used for each piece of content. This can be achieved by implementing 301 redirects from non-canonical URLs to the canonical URL.
// Define an array of canonical URLs for each piece of content
$canonical_urls = [
'page1' => '/page1',
'page2' => '/page2',
'page3' => '/page3',
];
// Get the current requested URL
$current_url = $_SERVER['REQUEST_URI'];
// Check if the current URL is a non-canonical URL
if (!in_array($current_url, $canonical_urls)) {
// Redirect to the canonical URL with a 301 status code
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $canonical_urls[array_search($current_url, $canonical_urls)]);
exit();
}
Related Questions
- What is the best practice for sorting multiple arrays in PHP based on a specific array?
- How can PHP be used to dynamically populate dropdown menus with values from a database table?
- How can developers ensure the accuracy and efficiency of color inversion functions in PHP, considering different color formats and representations?