htaccess规则处理所有通过index.php的请求,但图像和web资源带有查询字符串


htaccess rule to process all requests through index.php but images and web resources WITH a query string

所以,我正在为现有网站编写或实现基于PHP的URI路由器,并希望通过index.php(或router. PHP或任何文件)传递所有URL请求。

我已经通过使用下面的htaccess文件

成功地完成了这个任务
RewriteCond %{REQUEST_URI}  !('.png|'.jpg|'.gif|'.jpeg|'.js|'.css|'.ico)$
#RewriteCond %{QUERY_STRING} ^size=([a-z]*)$
RewriteRule (.*)  index.php [QSA]

这段代码按照预期通过index.php路由所有内容,但是一些图像请求需要一个查询字符串来响应大小。

例如www.mydomain.com/images/my_great_image.jpg?size=small

正如你所看到的,我一直在尝试某种解决方案(第二注释行代码),但是我根本不是很擅长Regexes和Apache规则。

这些查询字符串应该始终具有相同的模式^?Size =*和不同的查询字符串不应该传递。

也不应该事先违反响应式图像重写规则。(在index.php重写规则之前)

RewriteRule '.(?:jpe?g|gif|png)$ adaptive-images.php

谢谢你的帮助!

PD:我正在考虑添加一个相当简单的URL路由器,有什么好的基于PHP的建议吗?

我一直在研究chriso/klein.php和nikic/FastRoute

您可能应该使自适应图像php文件也被index.php路由规则排除。重写引擎循环,因此重写到php文件的第一个规则最终将被index.php规则捕获。试一试:

RewriteRule '.(?:jpe?g|gif|png)$ adaptive-images.php [L]
RewriteCond %{REQUEST_URI}  !('.png|'.jpg|'.gif|'.jpeg|'.js|'.css|'.ico|'.php)$
RewriteRule (.*)  index.php [QSA,L]

如果目标是只允许通过adaptive-images.php而不路由到index.php,那么您需要添加一个新条件:

RewriteRule '.(?:jpe?g|gif|png)$ adaptive-images.php [L]
RewriteCond %{REQUEST_URI}  !('.png|'.jpg|'.gif|'.jpeg|'.js|'.css|'.ico)$
RewriteCond %{REQUEST_URI} !adaptive-images'.php
RewriteRule (.*)  index.php [QSA,L]