PHP: 301 Redirect

In PHP, you can use the built-in header() function to set up a permanent 301 redirect.

Here is the modern, streamlined snippet to get it done:

<?php 
header('Location: http://example.com', true, 301);
exit(); 
?>

Just place this code at the very top of your PHP page. It will immediately redirect visitors to example.com. You can easily swap out that target URL for any domain, subdomain, or specific file path you prefer.

(Note: You might still see an older, two-line approach in legacy codebases. Thanks to Christian Häusler for the tip on using the cleaner, updated method above!)

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://example.com");
exit();
?>

Thank you for reading.

I'm Feeling Lucky
Darryl Dias

Written by Darryl Dias

The AI guy and founder of Caprycon, building AI-powered tools, exploring emerging technologies, and sharing insights from the world of artificial intelligence