通过.htaccess将旧域重定向到新域

时间:2012-03-18 13:57:13

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

我正在使用Apache Mod-Rewrite moduled及其.htaccess文件将旧域迁移到新域。 我们有几乎相同的新域结构,包括

  1. URL的
  2. 数据库
  3. 除了域名,就像是www.oldurl.com,现在它像www.newurl.com,这就是我在旧域.htaccess文件中的内容

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^oldurl.com$ [OR]
    RewriteCond %{HTTP_HOST} ^www.oldurl.com$
    RewriteRule (.*)$ http://www.newurl.com/$1 [R=301,L]
    

    以上设置似乎工作正常,但在一种情况下,我们在旧域中的URL很少,已删除或结构已更改,所以在这种情况下上面的规则将无法工作。我开始知道添加的东西在我上面描述的.htaccess文件中就像这样

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^oldurl.com$ [OR]
    RewriteCond %{HTTP_HOST} ^www.oldurl.com$
    RewriteRule (.*)$ http://www.newurl.com/$1 [R=301,L]
    Redirect 301 /my-page http://www.newurl.com/your-page
    

    我总共有20多个这样的网址,我想知道我是否需要将所有20多个网址映射到新网址,我需要注意它们应该放在文件中的任何顺序。< / p>

    我也想知道Apache将如何工作,它会查看每个匹配的映射URL吗?或者它以其他方式工作?

1 个答案:

答案 0 :(得分:1)

Redirect指令不会受到RewriteCond条件的约束,并且始终会将 / my-page 重定向到 http:// www。 newurl.com/your-page ,同样,mod_rewrite优先于mod_alias,因此{/ 1}}规则在 RewriteRule (.*)$ http://www.newurl.com/$1 [R=301,L]指令被查看之前应用。但是,如果.htaccess文件位于 oldurl.com newurl.com 域的文档根目录中,则Redirect指令将在浏览器被重定向到http://www.newurl.com/my-page,从而重定向(再次)到http://www.newurl.com/your-page

因此,因为mod_rewrite首先被应用,所以这些顺序并不重要。如果您有20个网址需要在新网站上重定向到新网址,则可以在自己的Redirect中对每个网址进行枚举。否则,如果您不想让浏览器重定向两次,您可以使用mod_rewrite引擎枚举它们:

Redirect

请注意,订单 在这里很重要。不得不重复HTTP_HOST的2个条件有点难看,你可以通过使用SKIP解决这个问题,但重复它们可能更好。但是,如果您有权访问您的服务器配置或vhost配置,请查看RewriteMap Directive,它允许您创建一个映射,在您的情况下,旧网址到新网址,您可以减少所有个人更改url重写为一个:

在服务器/ vhost配置中,如下所示:

RewriteEngine On

# redirect the changed URLs individually
RewriteCond %{HTTP_HOST} ^oldurl.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.oldurl.com$
RewriteRule ^my-page$ http://www.newurl.com/your-page [R=301,L]

RewriteCond %{HTTP_HOST} ^oldurl.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.oldurl.com$
RewriteRule ^my-page2$ http://www.newurl.com/your-page2 [R=301,L]

RewriteCond %{HTTP_HOST} ^oldurl.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.oldurl.com$
RewriteRule ^my-page3$ http://www.newurl.com/your-page3 [R=301,L]

# Finally, redirect everything else as-is
RewriteCond %{HTTP_HOST} ^oldurl.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.oldurl.com$
RewriteRule (.*)$ http://www.newurl.com/$1 [R=301,L]

/path/to/file/map.txt 的位置如下:

RewriteMap newurls txt:/path/to/file/map.txt

您的组合规则如下:

my-page your-page
my-page2 your-page2
my-page3 your-page3
etc...