---
title: "Apache 301跳转"
author: "Callan"
date: "2010-01-29T11:51:52Z"
tags: []
categories: ["Web前端"]
slug: "apache-301"
draft: false
lastmod: "2010-01-29T11:51:52Z"
id: 583216
url: "https://callan.iteye.com/blog/583216"
---

比如网站可以通过tu17.com访问，也可以通过[www.tu17.com](http://www.tu17.com)访问。所以想实现tu17.com全部重定向（跳转）到[www.tu17.com](http://www.tu17.com)。同时按照google的建议，使用服务器端 301 重定向，为了确保用户及搜索引擎定向至正确网页的最佳方法。301 状态代码表示某网页已被永久迁移至新位置。下面将了解一下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.tu17.com/new.htm
Redirect permanent /one http://tu17.com/two
RedirectMatch 301 (.*)\.gif$ http://www.tu17.com/images/$1.jpg
```

 

#### 2.使用mod\_rewrite重写URL方式

APACHE

```
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^tu17\.com
RewriteRule ^(.*)$ http://www.tu17.com/$1 [R=permanent,L]
```

 

在这里判断当前服务器变量HTTP\_HOST是否等于tu17.com,为真就进行重写，按照R=permanent进行永久重定向，L表示并立即停止重写操作，并不再应用其他重写规则

下面是我最终实现的.htaccess文件，同时也并入wordpress重写规则。

APACHE

 

```
<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]
</IfModule>
```