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();
}