Na navigaci | Klávesové zkratky

HTTP Redirection

For some, this is obvious, for me, it's mainly a cheat sheet. I just can't remember extremely long numbers, meaning those that have more than one digit.

In PHP, redirection is implemented with the following code:

$code = 301; // code in the range 300..307
$url = 'http://example.com';
header('Location: ' . $url, true, $code);
die('Please <a href="' . htmlSpecialChars($url) . '">click here</a> to continue.');

Note that after calling the header() command, it is necessary to explicitly terminate the script. It doesn't hurt to offer a text message and a link for agents that do not automatically redirect.

Types of Redirection

The meanings of individual codes are described in detail in the standard RFC 2616: HTTP/1.1 Redirection. Here they are:

300 Multiple Choices

There are several URLs to which redirection is possible (pages may differ, for example, in language). Offer users a list of these. The preferred destination can be indicated in the Location header; not every browser automatically redirects. Rarely used.

301 Moved Permanently

Use this when a resource that used to exist at the requested URL is now (permanently) located at a new address. Specify this in the Location header. However, if it has been discontinued, announce this with the code 410 Gone.

302 Found

A problematic code. It indicates that the resource has been temporarily moved elsewhere and the browser should access the new URL using the same method (GET, POST, HEAD, …) as used on the original. Additionally, with methods other than GET and HEAD, user confirmation should be required for the redirection. Most browsers, however, do not respect this and change the method to GET without requiring confirmation.

The code is often mistakenly used instead of 303.

303 See Other – for PRG

The Post/Redirect/Get technique prevents double submission of forms upon page reload or back button click. After submitting a form using the POST method, a redirection is made using the GET method to another page. This is exactly what the 303 code is for, converting POST to GET.

304 Not Modified

For caching purposes. It responds to the If-Modified-Since header that the resource has not changed since the previous visit. The response must not contain a body, only headers.

307 Temporary Redirect

As mentioned, code 302 has become problematic due to non-compliance with the standard by both web designers and browser creators. Code 307 is its reincarnation, which mostly works correctly. It can be used, for example, to perform a redirection using the POST method with transferred data.


phpFashion © 2004, 2024 David Grudl | o blogu

Ukázky zdrojových kódů smíte používat s uvedením autora a URL tohoto webu bez dalších omezení.