Redirect in PHP: How to set up forwarding
In this practical tip we will show you how to set up a redirect in PHP and thus automatically redirect the visitor to another website.
Setting up the redirect in PHP: status 301 or 302?
If the server redirects to another website via PHP, this is done by default with the status code 302.
- However, the status code 302 means that the page is only forwarded temporarily. A permanent forwarding is signaled by the status code 301.
- This makes no difference to the visitor - in any case, he will be automatically redirected to the other website.
- However, this difference is very interesting for search engines. If a robot receives status 302 from Google or other search engines, it assumes that this forwarding is only temporary.
- When the status code 301 is indicated, the search engine is informed that it is no longer necessary to search under the old URL, but instead via the permanent redirect. In simple terms, this means that the index can now exchange the old address for the new one.
- This means that the search engine does not have to start all over again when crawling the possibly new content of the website that has been redirected to.
How to set up redirect in PHP
The PHP code must be at the very beginning, no other output to the browser is allowed beforehand.
- Therefore, make sure that there is neither an "echo" nor an accidental space before the php tag. By the way, we explain exactly what PHP is in another post.
- To create a redirect to another website, enter the following code:
- Replace "www.domain.de" with your old URL and "der-neue-name.php" refers to the website to be redirected to.
- You should definitely insert the "exit". It prevents the forwarding from being executed incorrectly.
We will show you how to insert a picture using PHP in our next practical tip on programming.