Menu

How to disable Chrome info bars in Codeception Acceptance tests?

How to continue script execution in background in PHP?

How to create permanent redirect in PHP?

php http header redirect permanent

Often we need to instruct browser that the URL has been moved to another location. This can be done in PHP by sending proper HTTP headers with header function. The very first example in PHP documentation shows redirect example, however by default this is treated as temporary redirection. This means that browser will check this every time, and also crawling bots might index old URL. In most cases we want to have redirection permanent

To redirect browser to another location with PHP, the header function can be used to send headers instructing browser to open another address in the same window, without actually displaying anything. This function must be called before sending any output, or PHP will issue warning that the "Headers are already sent" and fail to fulfill redirection task.

Location Header

To redirect browser the Location header must be sent, which will instruct browser that the URL is moved currently to another location. That is, the browser will check again and again this URL if should still redirect, for example:

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

After sending redirect header it is usually fine to finish further code execution with exit instruction.

Redirect Permanent Example

To instruct browser and especially search engines robots, that the URL should be accessed with only new location, the redirect permanent headers should be sent. These instruction are not so obvious like the location header. The best method is to send 301 HTTP status before redirection, then exit:

<?php
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://meno.pro/');
exit;

See Also