下面将了解一下apache下实现301永久性重定向2个方法,需要具有访问服务器的 .htaccess 文件的权限。
1. Apache模块 mod_alias的 Redirect 和 RedirectMatch命令
上面提到2个命令使用方法相似。而区别就是后者RedirectMatch基于正则表达式匹配对当前的URL发送一个外部重定向语法为:
Redirect [status] URL-path URL
RedirectMatch [status] regex URL
status参数可以使用以下HTTP状态码:
permanent
返回一个永久性重定向状态码(301),表示此资源的位置变动是永久性的。
temp
返回一个临时性重定向状态码(302),这是默认值。
seeother
返回一个“参见”状态码(303),表示此资源已经被替代。
gone
返回一个“已废弃”状态码(410),表示此资源已经被永久性地删除了。如果指定了这个状态码,则URL参数将被忽略。
举例:
APACHE
Redirect 301 /old/old.htm http://www.zivee.cn/new.htm Redirect permanent /one http://zivee.cn/two RedirectMatch 301 (.*).gif$ http://www.zivee.cn/images/$1.jpg |
2.使用mod_rewrite重写URL方式
APACHE
Options +FollowSymLinks RewriteEngine on RewriteCond %{HTTP_HOST} ^zivee.cn RewriteRule ^(.*)$ http://www.zivee.cn/$1 [R=permanent,L] |
在这里判断当前服务器变量HTTP_HOST是否等于zivee.cn,为真就进行重写,按照R=permanent进行永久重定向,L表示并立即停止重写操作,并不再应用其他重写规则
下面是我最终实现的.htaccess文件,同时也并入wordpress重写规则。
APACHE
# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On #Redirect Options +FollowSymLinks RewriteCond %{HTTP_HOST} ^zivee.cn$ RewriteCond %{HTTP_HOST} !^$ RewriteRule ^(.*)$ http://www.zivee.cn/$1 [R=301,L] #Rewrite(blog) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^blog/.* /blog/index.php [L] RewriteRule . - </IfModule> # END WordPress |