如何编写重写条件以处理请求文件名与指定文件名不同的情况

5
我遇到了一个关于htaccess的问题,我想编写一个条件来阻止提供指定的文件。
如果请求的文件名存在,就简单提供它,所以我有以下代码:
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .? - [L]

但是如何实现不提供特定文件的服务呢?我有一个用于控制器操作的路径。例如,example/do_something.php 是指向文件 do_something.php 的路径,也是指向我的控制器动作的路径,我希望我的htaccess文件只提供此操作而不提供该文件。
2个回答

0
你可以直接使用这个规则:
RewriteRule ^example/do_something\.php$ - [L,NC]

这将跳过所有规则中在此规则下面的do_something.php


所以我只需要在该条件下面的所有规则的重写条件后添加这个吗? - vardius
抱歉,我没明白。您想使用这个规则做什么?能否给一些例子来说明吗?另外最好将完整的 .htaccess 放在问题中。 - anubhava
谢谢帮忙,但它没有起作用。如果你想知道我是如何解决它的,请查看我的答案。 - vardius
请查看答案中的更新规则,这应该是您的第一条规则。 - anubhava
好的,您已将“example”添加到路径中,这样它就与我的示例相匹配了,但仍然无法工作。 - vardius

0

我按照anubhava在他的answer中所说的尝试了一下。

RewriteRule ^do_something\.php$ - [L,NC]

对我来说它没有起作用,但我设法通过将这些文件重定向到我的前端控制器来解决它:

RewriteRule ^example/(.+)\.php$ %{ENV:BASE}/app.php [L]

所以在这种情况下,如果有人输入路径example/do_something.php,该文件将不会被提供服务,请求将通过前端控制器进行处理。

完整示例:

# If the requested filename exists
# And my route path for controller action is the same
# Don't serve file serve action
RewriteRule ^example/(.+)\.php$ %{ENV:BASE}/app.php [L]

# If the requested filename exists, simply serve it.
# We only want to let Apache serve files and not directories.
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .? - [L]

# Rewrite all other queries to the front controller.
RewriteRule .? %{ENV:BASE}/app.php [L]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接