【发布时间】:2011-03-14 10:56:22
【问题描述】:
我喜欢 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 sn-p 以重定向到正确的域名(无论如何,每个 html 文件都会附加一个简短的配置文件),但这可能不是一个好习惯。
有什么想法吗?
【问题讨论】:
标签: php apache .htaccess url-rewriting