Are there best practices for handling URL redirects and rewriting in PHP to avoid duplicate content?

When handling URL redirects and rewriting in PHP, it is important to use proper redirection techniques like 301 redirects to avoid duplicate content issues. Additionally, ensure that your canonical URLs are correctly set to point to the preferred version of the URL. Regularly check for and fix any redirect loops to prevent crawling and indexing errors by search engines.

// Check if the requested URL is not the canonical URL
if ($_SERVER['REQUEST_URI'] != '/canonical-url') {
    // Redirect to the canonical URL with a 301 status code
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: http://example.com/canonical-url');
    exit();
}