我想这将是一个愚蠢的问题,但我不明白这里发生了什么。我想通过 .htaccess 文件中的正则表达式匹配一组特定的 URI。
我想要以下内容
- 所有不包含 . 的文件
- 所有以 .htm/.html 结尾的文件
- 所有以 .php 结尾的文件
所以:
^[^.]+$
用于匹配 URI 中没有点的所有文件。
\.html?$
匹配所有 .html/.htm 文件
(^[^.]+$)|(\.html?$)
似乎将两者结合起来
(^[^.]+$)|(\.html?$)|(\.php$)
无法将内容与以 php 大小写结尾的匹配文件结合起来。例如 test.jpg 现在匹配,而它不应该匹配。
我一定遗漏了一些明显的东西。 它是什么?谢谢。
更新:这是我使用的整个上下文:
### REWRITE RULES ###
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (^[^.]+$)|(\.html?$)|(\.php$) bootstrap.php [L,QSA]
bootstrap.php 包含:
echo "testing bootstrap";
查询一个不存在的.jpg
http://localhost/test.jpg
给我这个输出:
testing bootstrap
...
更新 2:
在测试下面的第一个答案后,我发现使用简单的:
RewriteRule \.php$ bootstrap.php [L,QSA]
失败的方式与上述相同。它匹配 test.jpg。尽管在服务器配置或 .htaccess 文件中没有什么疯狂的......除了我已经发布的内容之外,这就是 .htaccess 文件中的所有内容:
AddType application/x-httpd-php .html
AddType application/x-httpd-php .xml
DirectoryIndex index.php
ErrorDocument 404 /errors/404.php
回答:(8 小时后无法回答我自己的问题...)
谢谢大家帮助我。
特别感谢@mario,他通过下面的评论帮助我解决了这个问题。
这确实是一个愚蠢的问题。这是发生的事情:
重写日志:
strip per-dir prefix: D:/Web_Root/test.jpg -> test.jpg
applying pattern '\.php$' to uri 'test.jpg'
pass through D:/Web_Root/test.jpg
strip per-dir prefix: D:/Web_Root/errors/404.php -> errors/404.php
applying pattern '\.php$' to uri 'errors/404.php'
RewriteCond: input='D:/Web_Root/errors/404.php' pattern='!-d' => matched
rewrite 'errors/404.php' -> 'bootstrap.php'
...
所以问题是我的 404 文档以 *.php 结尾,这就是 *.jpg 匹配未找到文件的原因。啊 bat ,这个我要找很久了...
这样就可以了:
RewriteRule ([^4]?[^0]?[^4]\.php) bootstrap.php [L,QSA]
那么,完整问题的答案是:
RewriteRule (^[^.]+$)|(\.html?$)|([^4]?[^0]?[^4]\.php) bootstrap.php [L,QSA]
再次感谢大家。
最佳答案
[Ok, this was not the specific solution here, but I'll make it a faux answer.]
当 mod_rewrite 规则出错时,启用 RewriteLog
有时会有所帮助.它需要在 httpd.conf
或 VirtualHost
部分进行配置,因此有点费力。但是 Apache 将列出它执行的顺序和处理操作以及 URL。这有助于查看正则表达式是否被 Apache 理解并按其应有的方式运行。
请注意,它有时可以保持为空 - 如果实际错误源是 Alias
和 Redirect
规则,甚至是 FileMatch
部分。在这种情况下,error.log
或什至只是 access.log
可能包含一些提示。
如果都失败了,你可能幸运地暂时启用了Nanoweb
而不是 Apache 。它带有一个类似的 mod_rewrite
实现,但是它使用 PHPs preg_match
PCRE 后端。 (不说我为什么知道。)
关于php - 正则表达式匹配.htaccess中的一系列文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6076845/