如何通过.htaccess永久重定向(301)?

时间:2010-07-10 00:07:28

标签: .htaccess redirect http-status-code-301

嘿伙计们!你能告诉我如何修改我的.htaccess吗

http://example.com (non-www without trailing slash)
http://example.com/ (non-www with trailing slash)
http://www.example.com (www without trailing slash)

将被永久重定向(301)到

http://www.example.com/ (www with trailing slash)

此外,是否有一般规则将此“行为”应用于子文件夹

http://example.com/subfolder
http://example.com/subfolder/
http://www.example.com/subfolder
=> http://www.example.com/subfolder/

子域名(反过来)

http://www.subdomain.example.com
http://www.subdomain.example.com/
http://subdomain.example.com
=> http://subdomain.example.com/

也是?因为我对此完全陌生,请善待...... =)

谢谢! NEL

3 个答案:

答案 0 :(得分:2)

DirectorySlashes指令负责处理尾随斜杠问题。

非www到www重定向是:

RewriteCond %{HTTP_HOST} !^(www\.example\.com)?$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

答案 1 :(得分:1)

这三条规则应该做你想要的所有事情:

RewriteEngine On

# Rewrite www.subdomain.example.com to subdomain.example.com
RewriteCond %{HTTP_HOST} ^www\.(.*)\.example\.com
RewriteRule (.*) http://%1.example.com/$1 [L,R=301]

# Rewrite example.com to www.example.com
RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule (.*) http://www.example.com/$1 [L,R=301]

# Add trailing slash to all URIs without one
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L,R=301] 

答案 2 :(得分:0)

我认为这会解决问题:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L,R=301]