开发者

How to implement 301 redirection with PHP/Apache?

When user is visiting by www.domain.name, redirect to domain.name开发者_StackOverflow.


RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.domain\.name$ [NC]
RewriteRule (.*) http://domain.name/$1 [R=301,QSA,L]


Put this in an .htaccess file in your root directory of your website:

RewriteEngine On
RewriteCond %{HTTP_HOST} . 
RewriteCond %{HTTP_HOST} !^domain\.name 
RewriteRule (.*) http://domain.name/$1 [R=301,L,QSA]

This is what they do, in order:

  1. Turn the rewrite engine on
  2. Make sure that HTTP_HOST was provided
  3. If it doesn't start with the name without the www or any other sub domain, then allow the rewrite to continue. This prevents an endless redirect back to itself.
  4. Grab everything after the URL (.*), including the querystring QSA, and redirect R=301 to the correct domain. The L just says this is the last command in the file if a match is found.


In Apache you add a Redirect line to your configuration files. In php you reply with a status code 301 and a Location: header.

However, a redirect requires an additional network round trip. Are you sure you don't want to just use a ServerAlias line so that the same content is served up whether they visit with or without the www.?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜