在RewriteRule语句中使用目录名称

时间:2012-01-26 10:23:33

标签: apache mod-rewrite

我想创建一个RewriteCond / RewriteRule组合,获得这个结果:

  

www.domain.com/dir1/old_file.php?a=1 => www.domain.com/dir1/a/1

     

www.domain.com/dir2/dir3/old_file.php?b=2 => www.domain.com/dir2/dir3/b/2

任何提示?


我正在尝试这样的事情:

RewriteCond %{QUERY_STRING} ^(.*)\=(.*)$
RewriteRule ^(.*)$ /$1/%1/%2? [R=301,L]

但结果不是我想要的:

curl -I "http://localhost/testsite/web/dir1/a.php?b=c"

HTTP/1.1 301 Moved Permanently
Date: Thu, 26 Jan 2012 10:36:15 GMT
Server: Apache/2.2.20 (Ubuntu)
Location: http://localhost/dir1/a.php/b/c
Vary: Accept-Encoding
Content-Type: text/html; charset=iso-8859-1

.htacces位于%{DOCUMENT_ROOT}/testsite/web/.htaccess

2 个答案:

答案 0 :(得分:0)

您是否需要在Web服务器上执行此操作?由于旧链接指向PHP脚本,您可以使用:

header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.newplace.com/");

由于您需要从当前位置确定新位置,因此您需要使用以下内容:

$_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];

然后针对此字符串执行REGEX以确定重定向的真实位置。

答案 1 :(得分:0)

(.*)中的

RewriteRule与请求的网址减去 .htaccess文件的位置相匹配。

如果/testsite/web/foo/bar是请求的网址且文件位于/testsite/web/,则/foo/bar仅匹配。

您需要像这样调整重写规则:

RewriteRule (.*) /testsite/web/$1/%1/%2 [R=301,L]