php强制用户转向www域名的方法
本文实例讲述了php强制用户转向www域名的方法。分享给大家供大家参考。具体分析如下:
有时候网站的www域名和非www域名都能访问网站,但是这样不利于搜索引擎的收录,会分散网页的权重,所以希望用户访问非www的域名时通过301永久重定向到www域名,例如用户访问jb51.net会直接转向www.nhooo.com,本php代码考虑了无法通过head重定向的情况,会在页面上输出链接,让用户点击。
//Installinfo.:
//Copyandpastetheselinesintoyourdefaultindex.phpor
//thefilethatget'scalledifavisitorcomesonyour
//website...
//readthehostfromtheserverenvironment
$host=$_SERVER["HTTP_HOST"];
//fixhostname-wenevernow...;-)
$host=strtolower($host);
$host=trim($host);
//Thisisimportant:
//WebbrowserslikeFirefoxaredoingtheirrequestwithout
//theportnumberlike"www.nhooo.com"butsomeother
//applicationssendhostnameslike"www.nhooo.com:80"
$host=str_replace(':80','',$host);
$host=trim($host);
//ifthehostisnotstartingwithwww.redirectthe
//usertothesameURLbutwithwww:-)
if($host!='www.nhooo.com'){
//Youanalsochangethe"!="to"==",ifyouwanttoforce
//theusertousethedomainnamewithoutthewww.
//sendstatusheader,sothatsearchenginesorotherservices
//detectthatthisisapermanentredirectandnotatemporary
header('HTTP/1.1301MovedPermanently');
//readtheURLtheuserrequested:
$url=isset($_SERVER["REQUEST_URI"])?$_SERVER["REQUEST_URI"]:'';
//redirecttheusertothenewdestination:
header('Location:https://www.nhooo.com'.$url);
//Convert"special"chars--causewenevernow...;-)
$url=htmlspecialchars($url);
//"fallback"link,ifthebrowserisnotsupportingheaderredirects
print'<ahref="https://www.nhooo.com'.$url.'">Pleaseclickhere</a>';
//stopthescriptexecutionhere
exit;
}
//Ifthedomainiswww.nhooo.comthengoonwithyourPHPcode
//ofwithyourwebsite...
//BTW:Youneedtoreplacejb51.nettroughyourowndomain:-D
希望本文所述对大家的php程序设计有所帮助。