Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

.htaccess - 301 or 302 Redirection With PHP

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'];
if (preg_match("/192.168.0.1/",$visitor)) {
    header('Location: http://www.yoursite.com/thank-you.html');
} else {
    header('Location: http://www.yoursite.com/home-page.html');
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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

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):

<?php
header("HTTP/1.1 503 Service Unavailable");
header("Status: 503 Service Unavailable");
header("Retry-After: 3600");
?><!DOCTYPE html>
<html>
<head>
<title>Temporarily Unavailable</title>
<meta name="robots" content="none" />
</head>
<body>
   Your message here.
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...