[背景]
這是我的應用程式的結構:
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/成為的http://localhost/BU/cs-602/developer-story/public/index.phpURL 和類似http://localhost/BU/cs-602/developer-story/user/id成為的 URL http://localhost/BU/cs-602/developer-story/public/index.php?p=user/id。
這是一個現場htaccess 測驗。
[問題]
如何修復.htaccess檔案或RedirectMatch將請求重定向到資源之類的規則CSS或JS檔案?當前規則在測驗儀中有效,但在我的服務器上無效,除非我洗掉該RedirectMatch規則。
我希望在我的 HTMLhttp://localhost/BU/cs-602/developer-story/css/main.css中成為這樣的 URL,我會執行以下操作: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]
uj5u.com熱心網友回復:
在查看服務器上的錯誤日志后,我找到了解決方案。我的各種嘗試都導致了重定向回圈。這是我的作業.htaccess檔案,以防它幫助任何嘗試做類似事情的人。
關鍵是在必要時使檔案短路,.htaccess這樣它就不會無限地重寫你的 URL。我添加了行內注釋來解釋該程序:
# Redirect all requests to the public directory.
<IfModule mod_rewrite.c>
RewriteEngine On
# Only needing for local develoment in my case.
RewriteBase /BU/cs-602/developer-story/
# If nothing or an index page is requested go to `public/index.php` and stop processing.
RewriteRule ^(\/||.*index\..*)$ public/index.php [L,QSA]
# If the URL already contains the `public/` directory go to URL and stop processing.
RewriteRule ^(.*public\/.*)$ $1 [L,QSA]
# If it appears this URL is for a resource (JS, CSS, etc.) prefix with `public/`.
RewriteCond %{REQUEST_URI} ^([\w\d\s\-\_\/\%]*)\.(?!php|htm|html).*$
# Go to the modified URL if the last rule triggered and stop processing.
RewriteRule ^(.*)$ public/$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
# Rewrite all remaing URLs to our apps MVC structure.
RewriteRule ^([\w\d\s\-\_\/\%]*)$ public/index.php?p=$1 [L,QSA]
</IfModule>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/430780.html
