Htaccess 301 跳转配置案例

一、新老域名之间的跳转

新老域名跳转:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursite.com [NC]
RewriteRule ^(.*)$ http://www.yoursite.com/$1 [L,R=301]
RewriteBase /

如果有多个域名:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursite1.com [OR]
RewriteCond %{HTTP_HOST} ^www.yoursite1.com [OR]
RewriteCond %{HTTP_HOST} ^www.yoursite2.com [OR]
RewriteCond %{HTTP_HOST} ^yoursite.com$ [NC]
RewriteRule ^(.*)$ http://www.yoursite.com/$1 [L,R=301]
RewriteBase /

二、移除URL地址中出现 index.php 形式的结尾

跳转 index.php 到根目录 /
在进行301 跳转时,可能发生跳转后在首页根目录露出 index.php 等默认文件名,比如要统一地址
http://www.sheshui.me/index.php 为 http://www.sheshui.me/ 的形式,则可配置为:

Options +FollowSymLinks
DirectoryIndex index.php
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\ HTTP/
RewriteRule ^index\.php$ http://www.yoursite.com/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

如果子目录 (比如:/blog ) 也默认从URL中移除index.php,则可配置为:

Options +FollowSymLinks
DirectoryIndex index.php 
RewriteEngine On
RewriteBase /blog/
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /blog/index\.php\ HTTP/
RewriteRule ^index\.php$ http://www.yoursite.com/blog/ [R=301,L] 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]

以上参考: http://www.askapache.com/htaccess/redirect-index-blog-root.html

三、主域名指向子目录的 Htaccess配置范例

# .htaccess main domain to subfolder redirect
# Copy and paste the following code into the .htaccess file
# in the public_html folder of your hosting account
# make the changes to the file according to the instructions.
# Do not change this line.
RewriteEngine on
# Change yourdomain.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?yourmaindomain.com$
# Change ‘subfolder’ to be the folder you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/subfolder/
# Don’t change this line.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change ‘subfolder’ to be the folder you will use for your main domain.
RewriteRule ^(.*)$ /subfolder/$1
# Change yourdomain.com to be your main domain again.
# Change ‘subfolder’ to be the folder you will use for your main domain
# followed by / then the main file for your site, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?yourmaindomain.com$
RewriteRule ^(/)?$ subfolder/index.php [L]

评论已关闭。Comments are turned off for this article.