重定向到.htaccess中的正确域名

时间:2011-03-14 10:56:22

标签: php apache .htaccess url-rewriting

我喜欢Paul Irish的HTML5 Boilerplate。我把.htaccess文件中的大部分内容都包含在我的内容中。

我喜欢它重定向到域的非www版本的方式,以及在它缺失时添加一个尾部斜杠:

# ----------------------------------------------------------------------
# Suppress or force the "www." at the beginning of URLs
# ----------------------------------------------------------------------
# The same content should never be available under two different URLs - especially not with and
# without "www." at the beginning, since this can cause SEO problems (duplicate content).
# That's why you should choose one of the alternatives and redirect the other one.
# By default option 1 (no "www.") is activated. Remember: Shorter URLs are sexier.
# no-www.org/faq.php?q=class_b
# ----------------------------------------------------------------------
# Option 1:
# Rewrite "www.domain.com -> domain.com" 
<IfModule mod_rewrite.c>
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteCond %{HTTP_HOST} ^m\.(.+)$ [NC]
  RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
</IfModule>
# ----------------------------------------------------------------------


# ----------------------------------------------------------------------
# Add/remove trailing slash to (non-file) URLs
# ----------------------------------------------------------------------

# Google treats URLs with and without trailing slashes separately.
# Forcing a trailing slash is usually preferred, but all that's really
# important is that one correctly redirects to the other.
# http://googlewebmastercentral.blogspot.com/2010/04/to-slash-or-not-to-slash.html
# http://www.alistapart.com/articles/slashforward/
# http://httpd.apache.org/docs/2.0/misc/rewriteguide.html#url Trailing Slash Problem
# ----------------------------------------------------------------------
# Rewrite "domain.com/foo -> domain.com/foo/"

<IfModule mod_rewrite.c>
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
  RewriteRule ^(.*)$ /$1/ [R=301,L]
</IfModule>
# ----------------------------------------------------------------------

但是,如果有几个停放的域(或别名)会发生什么?例如,如果主域名是www.domain.com但是停放了以下内容:www.domain.co.uk和www.domain2.com?上述代码并没有考虑到这一点,只会从www.domain.co.uk重定向到domain.co.uk,从www.domain2.com重定向到domain2.com。我希望他们都重定向到domain.com。理想情况下,我不想将正确的域名放在.htaccess文件中,因为我必须单独修改每个网站的.htaccess文件。也许这是唯一的方法,因为.htacess文件无法知道正确的域名 - 这是真的吗?我想在每个页面的顶部添加一个简短的php片段,以重定向到正确的域名(无论如何,每个html文件都会附加一个简短的配置文件),但这可能不是很好的做法。

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

IMO别名域应该获得自己的VirtualHost,它只包含Redirect语句。 除非您使用基于IP的VHost,否则VirtualHosts无论如何都需要包含域名。

答案 1 :(得分:1)

如果您希望所有域重定向到同一个域,请说domain.com,只需add this to your .htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} !^domain.com [NC]
RewriteRule ^(.*)$ http://domain.com%{REQUEST_URI} [R=301,L]