【发布时间】:2015-06-07 21:00:04
【问题描述】:
在一周的大部分时间里,我一直在努力解决这个问题,结果证明是同样的问题和解决方案,就像在这个线程中一样:RewriteCond in .htaccess with negated regex condition doesn't work?
TL;DR:我在某个时候删除了我的 404 文档。这导致 Apache 在尝试为新页面提供服务时再次运行规则并且无法运行。在第二次旅行中,它总是符合我的特殊条件。
我在使用这个正则表达式时遇到了无穷无尽的麻烦,我不知道是因为我遗漏了一些关于 RewriteCond 的东西还是什么。
简单地说,我只想匹配顶级请求,这意味着任何没有子目录的请求。例如我想匹配site.com/index.html,而不是site.com/subdirectory/index.html。
我想我可以用这个来完成它:
RewriteCond %{REQUEST_URI} !/[^/]+/.*
有趣的是,它不起作用但反过来却起作用。例如:
RewriteCond %{REQUEST_URI} /[^/]+/.*
这将检测何时有 子目录。它会忽略顶级请求 (site.com/toplevelurl)。但是当我将感叹号放在前面以反转规则(应该允许 RewriteCond)时,它会停止匹配任何内容。
我尝试了许多不同风格的正则表达式和不同的模式,但似乎都没有。任何帮助,将不胜感激。 this Stack Overflow 答案似乎应该回答它,但对我不起作用。
我还用这个.htaccess rule tester 对其进行了测试,我的模式在测试器中工作,它们只是在实际服务器上不起作用。
编辑:根据要求,这是我的 .htaccess。它允许 URL 没有文件扩展名,并且还执行类似于自定义 404 页面的操作(尽管它的目的是允许文件名作为参数,而不是 404 替换)。
Options +FollowSymLinks
DirectoryIndex index.php index.html index.htm
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
RewriteCond %{REQUEST_FILENAME} =/home/me/public_html/site/
RewriteRule ^(.*)$ index.php
RewriteCond %{REQUEST_FILENAME} !-f # Below this is where I would like the new rule
RewriteRule ^(.*)$ newurl.php
</IfModule>
【问题讨论】:
-
看起来您跳过了行开始和结束锚点。为什么?
-
这只是我尝试过的最新正则表达式;我也尝试过开始和结束锚点,是的。实际上最终版本应该使用它们,所以我会。