Php implements 301 permanent redirection and 302 temporary redirection methods

Source: Internet
Author: User


The principle of implementing redirection is very simple, that is, the Web server returns an HTTP header to the login visitor. The HTTP header sent by PHP is implemented by the header () function. 301,302,404 these status codes are agreed in the HTTP protocol, so you don't need to break the sandpot and ask "why is 301 instead of 3001 ". Go back to the question.

PHP 301 redirection:

The code is as follows: Copy code

Header ('http/1.1 301 Moved Permanently ');

Header ("Location: http://www.111cn.net /");

Exit ();

Or

The code is as follows: Copy code

<? Php
// 301 permanent redirection

$ Http_protocol = $ _ SERVER ['server _ protocol']; // http PROTOCOL version

// If it is another protocol, the default value is HTTP/1.0.
If ('http/1.1 '! = $ Http_protocol & 'HTTP/123 '! = $ Http_protocol)
$ Http_protocol = 'http/1.0 ';

// Response 301 status code
Header ("$ http_protocol 301 Moved Permanently ");

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

PHP 302 redirection:

The code is as follows: Copy code

Header ("Location: http: // www.Hzhui. Com /");

Exit ();

The PHP 404 error is also included with the following code:

The code is as follows: Copy code

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

Exit ();

Here we will talk about php 301 and 302 redirection. The following is an example of apache practice.

Example:

APACHE

The code is as follows: Copy code

Redirect 301/old/old.htm http://www.111cn.net/new.htm
Redirect permanent/one http://111cn.net/two
RedirectMatch 301 (. * 2.16.gif $ yun_qi_img/2.161.jpg


2. Use mod_rewrite to rewrite the URL

APACHE

The code is as follows: Copy code

Options + FollowSymLinks
RewriteEngine on
RewriteCond % {HTTP_HOST} ^ 111cn.net
RewriteRule ^ (. *) $ http://www.111cn.net/#1 [R = permanent, L]

For apache htaccess, the method of rewriting the URL is almost the same as that of mod_rewrite.

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.