繁体   English   中英

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

[英]Redirect to correct domain name in .htaccess

我爱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文件都会添加一个简短的配置文件),但这可能不是一个好习惯。

有任何想法吗?

IMO别名域应获得其自己的VirtualHost,其中仅包含Redirect语句。 除非您使用基于IP的VHost,否则VirtualHost仍需要包含域名。

如果您希望所有域都重定向到同一个域,例如domain.com ,只需将其添加到您的.htaccess

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM