将域上的所有请求重定向到特定URL

时间:2013-02-02 16:43:32

标签: apache .htaccess mod-rewrite redirect

自从我使用Apache(非常很长时间)以来已经有很长一段时间了,即便如此,我也没有真正做过很多URL重写或类似的事情,只是简单的托管。但现在我正在尝试将一个简单的重定向拼凑成一个重新命名为新域名的小型企业。

它的设置方式是旧域的主机有一个基于Web控制面板的重定向到特定的URL,这是“寻找旧的我们?”新域名的页面。所有请求都被重定向,但它们带有整个请求路径,导致新站点上有404。

我一直在浏览一些Apache文档以及一些我可以在网上找到的例子,但我还没有完成。我到目前为止离开的地方是这样的:

RewriteCond %{REQUEST_URI} .*looking-for-blah.* [NC]
RewriteRule ^ http://newsite.com/looking-for-blah [L,R=301]

这个想法是,任何包含looking-for-blah的路径的任何请求,无论其之前或之后是什么,都应该转到显式http://newsite.com/looking-for-blah。因此,当旧主持人将某人重定向到:

http://newsite.com/looking-for-blah/foo/baz

他们被新网站重定向到:

http://newsite.com/looking-for-blah

但是,它似乎没有捕获传入的请求并重定向它们。我在RewriteCond中遗漏了一些基本概念吗?也许有一种更好的方法可以做到这一点,我甚至没有考虑过?

编辑:这是整个.htaccess的当前状态:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# BEGIN custom redirect
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule looking-for-icamp http://empow.me/looking-for-icamp [L,R=301]
</IfModule>
# END icamp redirect

但在wget上执行简单的http://empow.me/looking-for-icamp/foo会产生404而不是所需的301。

1 个答案:

答案 0 :(得分:2)

Wordpress默认的catch-all路由符合您的规则,然后才能到达,因此您的规则需要放在上面任何Wordpress重写。我还添加了一个RewriteCond来比你的.+技巧更清楚地表明循环重写避免,这对我来说似乎有点笨拙,并且在后来的阅读中很难理解。

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# BEGIN custom redirect

# This must take place before the Wordpress redirect to index.php
# Added condition to avoid circular rewrite
RewriteCond %{REQUEST_URI} !^/looking-for-icamp$ 
RewriteRule looking-for-icamp http://empow.me/looking-for-icamp [L,R=301]
# END icamp redirect

# Note - you had two identical WP blocks. I've removed one.

# BEGIN WordPress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# This rule was the one blocking your custom rule earlier....
RewriteRule . /index.php [L]

# END WordPress
</IfModule>