【发布时间】:2022-02-12 05:00:00
【问题描述】:
[背景]
这是我的应用程序的结构:
app/
controllers/
...
modules/
...
views/
...
public/
css/
main.css
images/
...
js/
...
index.php
.htaccess
出于各种原因(安全、组织等),公共应用程序(网站)由public/index.php 加载和显示在我服务器的“根”我有以下.htaccess 文件:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /BU/cs-602/developer-story/
RewriteRule ^(\/||index\.*)$ public/index.php [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RedirectMatch ^(/BU/cs-602/developer-story.)([\w\d\s\/\-\:\_%\ ]*\.css)$ $1public/$2 [L]
RewriteRule ^([\w\d\-\_\/\ ]*)$ public/index.php?p=$1 [L,QSA]
</IfModule>
这些规则应该重写/重定向来自服务器“根”的所有请求到public/index.php 因为我在我的开发服务器上进行本地开发,所以这个项目实际上并不是我服务器的根目录,而是位于/BU/cs-602/developer-story/ 这是为什么我添加了RewriteBase 规则。
如果我删除 RedirectMatch 规则,从 MVC 的角度来看,一切正常:
像 http://localhost/BU/cs-602/developer-story 或 http://localhost/BU/cs-602/developer-story/ 这样的 URL 变成 http://localhost/BU/cs-602/developer-story/public/index.php 并且像 http://localhost/BU/cs-602/developer-story/user/id 这样的 URL 变成 http://localhost/BU/cs-602/developer-story/public/index.php?p=user/id。
这里是直播htaccess test。
[问题]
如何修复.htaccess 文件或RedirectMatch 规则以将请求重定向到CSS 或JS 文件等资源?当前规则在 tester 中有效,但在我的服务器上无效,除非我删除 RedirectMatch 规则。
我希望像 http://localhost/BU/cs-602/developer-story/css/main.css 这样的 URL 在我的 HTML 中变成 http://localhost/BU/cs-602/developer-story/public/css/main.css,我会这样做:
<img src="images/logo.png">
服务器实际加载:
<img src="public/images/logo.png">
这样我就不必在所有资源前面加上public/。
[披露]
这个问题是为了帮助我大学的一个期末项目,但这种类型的问题是允许的,并且不违反学术政策。用htaccess 和MVC 做一个项目不是必需的,我只是在做一些挑战自己的事情。
更新:
这是我原来的RedirectMacth 规则。任何不是 PHP 或 HTML 文件的东西都会被重定向:
RedirectMatch ([\w\d\s\/\-\:\_%\ ]*\.(?!php|htm|html)) $1 [L]
【问题讨论】:
标签: php apache .htaccess mod-rewrite