Thứ Sáu, 11 tháng 12, 2009

Generic non-www to www (and vice versa) 301 redirect using .htaccess

The problem:
I’ve always hardcoded the domain name in my htaccess’es, requiring me to make changes each time I deploy a new website.
The solution:
Behold, an alternate, generic method of redirecting non-www to www and www to non-www, requiring no changes between deployments!
Non-www to wwwRewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) http://www.%{HTTP_HOST}/$1 [R=301,L]
www to non-wwwRewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]
Bonus tip: Remove trailing slash from address line
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]
or :

$uniqueHost = ‘www.myWebSite.com’;
if (isset($_SERVER["HTTP_HOST"])) {
if ($_SERVER["HTTP_HOST"] != $uniqueHost) {
if (isset($_SERVER["REQUEST_URI"])) {
$redirect = ‘http://’.$uniqueHost.$_SERVER["REQUEST_URI"];
}
else {
$redirect = ‘http://’.$uniqueHost;
}
header(”HTTP/1.1 301 Moved Permanently”);
header(”Location: “.$redirect);
exit;
}
}
source : http://www.cakephp.nu/quick-tip-generic-nonwww-www-vice-versa-301-redirect-htaccess

Không có nhận xét nào:

Đăng nhận xét