PHP实现非www域名301重定向至www域名的方法
本内容介绍了利用PHP语言实现将用户强制引导至www域名的具体方案。此方法可供开发者参考与借鉴,下文将进行详细解析。
部分网站允许通过www前缀及无前缀两种形式访问,但这会削弱搜索引擎对网页权重的集中,影响收录效果。因此,建议配置当用户访问非www域名时,执行301永久重定向将其指向对应的www域名,例如从jb51.net跳转至www.jb51.net。相关PHP代码不仅处理了标准的头部重定向,还针对浏览器不支持Head重定向的情况做了兼容,会在页面上生成可见的跳转链接供用户点击。
// Install info.:
// Copy and paste these lines into your default index.php or
// the file that get's called if a visitor comes on your
// website...
// read the host from the server environment
$host = $_SERVER["HTTP_HOST"];
// fix host name - we never now... ;-)
$host = strtolower($host);
$host = trim($host);
// This is important:
// Webbrowsers like Firefox are doing their request without
// the port number like "www.jb51.net" but some other
// applications send host names like "www.jb51.net:80"
$host = str_replace(':80', '', $host);
$host = trim($host);
// if the host is not starting with www. redirect the
// user to the same URL but with www :-)
if ($host != 'www.jb51.net'){
// You an also change the "!=" to "==", if you want to force
// the user to use the domain name without the www.
// send status header, so that search engines or other services
// detect that this is a permanent redirect and not a temporary
header('HTTP/1.1 301 Moved Permanently');
// read the URL the user requested:
$url = isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : '';
// redirect the user to the new destination:
header('Location: https://www.jb51.net' . $url);
// Convert "special" chars -- cause we never now... ;-)
$url = htmlspecialchars($url);
// "fallback" link, if the browser is not supporting header redirects
print 'Please click here';
// stop the script execution here
exit;
}
// If the domain is www.jb51.net then go on with your PHP code
// of with your website...
// BTW: You need to replace jb51.net trough your own domain :-D
期望上述内容能为各位的PHP编程工作提供有价值的参考。