【发布时间】:2018-10-29 11:56:20
【问题描述】:
下面是我的站点目录结构:
htdocs/
My-Project/
.htaccess
public/
css/
img/
img.jpg
js/
index.php
...(other stuff)
我想使用 .htaccess 文件来检查请求的路径是否是 public/ 目录中的文件(类似于使用 express.static 从目录中提供静态文件)。如果是,则提供它,否则将请求转发到 /index.php。
基本上我的问题可以分为以下几个子问题:
子问题 1:仅提供公共目录中的文件,否则路由到 index.php
子问题 2:从公共目录提供这些文件在 URL 中没有(需要)“公共”
所以/My-Project/img/img.jpg 应该改写为/My-Project/public/img/img.jpg 但/My-Project/notexisting.file 或/My-Project/test应该改写为/My-Project/index.php。
到目前为止,这是我的想法:
RewriteEngine On
#Block 1
#Condition: File exists in public directory
RewriteCond %{DOCUMENT_ROOT}/My-Project/public/$1 -f
RewriteRule ^(.*)$ public/$1 [L]
#Block 2
#Condition: File doesn't exist in public directory
RewriteCond %{DOCUMENT_ROOT}/My-Project/public/$1 !-f
RewriteRule ^(.*)$ index.php [L,QSA]
当Block 1 独立时 -> SubProblem2 已解决,但只要添加 Block 2 以解决 SubProblem1,每个请求都会重写为 index.php。为什么会这样? 为什么第二个 RewriteCond 没有按预期工作?
【问题讨论】:
标签: php apache .htaccess mod-rewrite