Current Location: Home> Latest Articles> PHP Tutorial: How to Properly Implement 301 Permanent Redirect

PHP Tutorial: How to Properly Implement 301 Permanent Redirect

gitbox 2025-08-02

Introduction

A 301 redirect indicates that when a user visits a certain URL, the server permanently redirects the request to another URL and returns a 301 status code. This is commonly used for website URL structure changes, page migrations, or device-based redirection. Implementing a 301 redirect in PHP is straightforward, flexible, and efficient.

How PHP Implements 301 Redirects

Using the header() Function for Redirects

In PHP, you can send HTTP headers using the header() function and set the Location header to the target URL to perform a redirect.

header("Location: https://www.example.com/new-url", true, 301);
exit;

The above code redirects users to the specified URL and returns a 301 status code. The second parameter 'true' means it replaces any previous header with the same name.

Using http_response_code() with header()

Another method is to call http_response_code() to set the status code first, then set the Location header with header().

http_response_code(301);
header("Location: https://www.example.com/new-url");
exit;

This approach separates the status code from the redirect location, making the logic clearer.

Example Code

Below is a complete example demonstrating both ways to implement a 301 redirect:

$url = "https://www.example.com/new-url";

// Method One: Using header()
header("Location: $url", true, 301);
exit;

// Method Two: Using http_response_code() and header()
http_response_code(301);
header("Location: $url");
exit;

Important Notes

No Output Before Redirect

Before calling header(), there must be no output at all, including spaces, new lines, or HTML tags, otherwise the redirect will fail or cause warnings.

// Incorrect example
echo "Hello World!";
header("Location: https://www.example.com");
exit;

// Correct example
header("Location: https://www.example.com");
exit;

Order of Status Code Setting

If you use http_response_code() to set the status code, it must be called before setting the Location header with header(). Otherwise, the status code will default to 200 when the Location header is set.

// Incorrect example
header("Location: https://www.example.com");
http_response_code(301);
exit;

// Correct example
http_response_code(301);
header("Location: https://www.example.com");
exit;

Conclusion

Implementing 301 redirects in PHP is simple and practical. Whether adjusting URLs or redirecting based on devices, these methods can handle it easily. Just use header() and http_response_code() properly, and ensure no output is sent before headers, to guarantee stable and reliable redirects.