301 or 302 Redirection With PHP

05/04/2020 15:00:02

I'm considering using the following code during a website launch phase to show users a down for maintenance page while showing me the rest of the site.

Is there a way to show the correct 302 re-direction status to search engines or should I look for another .htaccess based approach?

$visitor = $_SERVER['REMOTE_ADDR'];
} else {

Verified Answer (129 Votes)

02/20/2012 20:38:25

For a 302 Found, i.e. a temporary redirect do:

// OR: header('Location: http://www.yoursite.com/home-page.html', true, 302);

If you need a permanent redirect, aka: 301 Moved Permanently, do:

header('Location: http://www.yoursite.com/home-page.html', true, 301);

For more info check the PHP manual for the header function Doc. Also, don't forget to call exit; when using header('Location: ');

But, considering you are doing a temporary maintenance (you don't want that search engines index your page) it's advised to return a 503 Service Unavailable with a custom message (i.e. you don't need any redirect):

header("HTTP/1.1 503 Service Unavailable");
header("Status: 503 Service Unavailable");
header("Retry-After: 3600");
?><!DOCTYPE html>
<title>Temporarily Unavailable</title>
   Your message here.

Answer #2 (17 Votes)

02/20/2012 20:39:21

The following code will issue a 301 redirect.

header('Location: http://www.example.com/', true, 301);

Answer #3 (7 Votes)

02/20/2012 20:52:30

I don't think it really matters how you do it, from PHP or htaccess. Both will accomplish the same thing.

The one thing I want to point out is whether you want the search engines begin to index your site in this "maintenance" phase or not. If not, you could use the status code 503 ("temporarily down"). Here's a htaccess example:

RewriteEngine on
RewriteCond %{ENV:REDIRECT_STATUS} !=503
ErrorDocument 503 /redirect-folder/index.html


header('Location: http://www.yoursite.com/redirect-folder/index.html', true, 503);

With the current PHP redirect code you're using, the redirect is a 302 (default).

Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.