PHP implements 301 permanent redirects and 302 temporary redirects

Source: Internet
Author: User

The principle of implementing redirection is simple: The Web server returns an HTTP header to the Liu Visitor, and the function of PHP sending the HTTP header is implemented by the header () function. 301, 302, 404 These Status codes are agreed in the HTTP protocol, so don't break the casserole to ask "why 301 instead of 3001". Get back to the point.

PHP 301 Redirect:

The code is as follows

Header (' http/1.1 moved Permanently ');

Header ("location:http://www.hzhuti.com/");

Exit ();

Or

The code is as follows

<?php
301 Permanent Redirect

$http _protocol = $_server[' Server_protocol ']; HTTP protocol version

If it is a different protocol, the default is http/1.0
if (' http/1.1 '!= $http _protocol && ' http/1.0 '!= $http _protocol)
$http _protocol = ' http/1.0 ';

Response 301 Status Code
Header ("$http _protocol moved Permanently");

Specify the redirected URL
$new _url = ' http://www.111cn.net/';
Header ("Location: $new _url");
?>

PHP 302 Redirect:

The code is as follows

Header ("location:http://www. ") Hzhuti. com/");

Exit ();

Along with the PHP 404 error also included:

The code is as follows

Header ("http/1.1 404 Not Found");

Exit ();

Here's a little bit about PHP 301 and 302 redirects here, and here's the Apache approach

Cases:

Apache

The code is as follows

Redirect 301/old/old.htm http://www.111cn.net/new.htm
Redirect Permanent/one Http://111cn.net/two
Redirectmatch (. *). gif$ $1.jpg

2. Use mod_rewrite to rewrite URL method

Apache

The code is as follows

Options +followsymlinks
Rewriteengine on
Rewritecond%{http_host} ^111cn.net
Rewriterule ^ (. *) $ http://www.111cn.net/$1 [r=permanent,l]

About Apache htaccess here is not a reference to the mod_rewrite rewrite the URL way is almost exactly the same OH.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.