PHP redirect: 301 and 302
Hundreds of developers subscribed to my newsletter.
Join them and enjoy free content about the art of crafting websites!
To perform a 302 redirect in PHP, use the header()
function to set the new location.
header('Location: https://example.com/path/to/page');
Easy, right? There’s one thing to remember going forward, though.
Table of contents

Don’t output text before sending headers
<?php echo 'Hello, World!'; header('Location: https://example.com/some/page');
This will result in a warning:
Warning: Cannot modify header information - headers already sent by
Stop code execution
Most of the time, you will need to stop code execution with the exit()
function. Here’s an example:
<?php if (! empty($_POST['redirect'])) { header('Location: https://example.com/some/page'); exit;} // The following code will never be executed thanks to exit().
If you don’t stop code execution, the user will be redirected to the new URL after the code has finished running.
Set the correct HTTP code
The header()
function can take a third parameter.
For instance, when you add a Location
header, the HTTP code will automatically be set to 302
.
But what if we want to perform a 301 redirect to the new URL instead?
header('Location: https://example.com/some/page', true, 301);
Frequently Asked Questions
Should a redirect be 301 or 302?
Most of the time, you should stick to the default 302 redirect, unless you want to permanently redirect your users.
Is 302 a permanent redirect?
302 redirects are not permanent.
What are 302 redirects used for?
302 redirects are used for the following scenarii:
- You have a promotion for a product and you want to redirect your visitors to it for a limited time, while preserving the ranking of your page on search engines results pages (or SERPs, for SEO nerds out there);
- A product is sold out, we need to redirect users to a new one for a limited time;
- A/B testing. You want to redirect some visitors to a another page, still without affecting your ranking.
What are 301 redirects used for?
The HTTP 301
code means the resource has been moved permanently.
Some use cases include:
- Redirect from HTTP to HTTPS;
- Redirect from www to non-www URLs;
- Redirect old URLs to new ones (we don’t want people to stumble upon dead links). This is useful when migrating to a new domain.
Which is better, a 301 or 302 redirect?
None is better than the other. Use whichever is the most appropriate to your needs. This article should help you figure it out.