重定向直接文件访问或重写,无需进一步重写和重定向

时间:2015-04-01 22:03:14

标签: apache .htaccess mod-rewrite redirect

我想立刻工作:

用户请求以/command/rewritehandler.php开头并被重定向到/的任何请求

或用户请求不以/command/开头的任何其他内容,如果用户请求/command/rewritehandler.php?q=fullpath,则转换为fullpath

RewriteEngine On
#Next two lines works with redirect
RewriteCond %{REQUEST_URI} ^/command/rewritehandler\.php
RewriteRule .* /? [L,R]
#Next two lines does expected rewritting without above two lines
RewriteCond %{REQUEST_URI} (.+)
RewriteRule !^command/ /command/rewritehandler.php?q=%1 [B,L]

但在预期重写后,它会被重定向到/。如何避免这种情况? L标记不会阻止其他RewriteRule在此处运行。背景:How to bypass %23 (hash sign) through RewriteRule without data loss?

1 个答案:

答案 0 :(得分:2)

在第一条规则中使用THE_REQUEST变量:

RewriteEngine On

#Next two lines works with redirect
RewriteCond %{THE_REQUEST} \s/+command/rewritehandler\.php [NC]
RewriteRule .* /? [L,R]

#Next two lines does expected rewritting without above two lines
RewriteCond %{REQUEST_URI} (.+)
RewriteRule !^command/ /command/rewritehandler.php?q=%1 [B,L]

THE_REQUEST变量表示Apache从您的浏览器收到的原始请求,并且在执行某些重写规则后不会被覆盖。此变量的示例值为GET /index.php?id=123 HTTP/1.1