[英]Best way to mod_rewrite images to /public
我試圖找出使我的網站上的所有內容都指向index.php的最佳方法,除了所有位於/ public中的圖像/ css / javascript。
這是我在.htaccess中嘗試過的兩部分方法,但是想知道是否有更好的方法或方法可以改進這兩種方法。
另外,我不確定在服務器上哪個更好(開銷更少)。
RewriteEngine on
RewriteBase /subfolder/
RewriteRule !\.(js|ico|txt|gif|jpg|png|css|pdf)$ index.php
RewriteRule ^.*/public/(.*)$ /subfolder/public/$1
#RewriteBase /subfolder
#RewriteCond %{REQUEST_URI} ^(?!/public/).+ [NC]
#RewriteRule !\.(js|ico|txt|gif|jpg|png|css|pdf)$ index.php [L]
任何人都對如何最好的方法有什么建議?
這是我為自己的框架所做的工作(“ STATIC
”環境變量的計算非常復雜,因此我刪除了目前可能過於復雜的“硬”部分):
# if the site is static (i.e. xx.static.mydomain.com)
RewriteCond %{ENV:STATIC} 1
# Try to assign the extension into an EXT variable:
RewriteRule (.*)(\.(css|js|htc|pdf|jpg|jpeg|gif|png|ico)){1}$ $1$2 [NC,QSA,E=EXT:$3]
# (!) if it's an image...
RewriteCond %{ENV:EXT} (jpg|jpeg|gif|png|ico) [NC]
# ...no matter the extension, change it to 'img' :
RewriteRule (.*) - [QSA,E=EXT:img]
# if it's static...
RewriteCond %{ENV:STATIC} 1
# ...and its extension is not empty:
RewriteCond %{ENV:EXT} !^$
# ...and the filename exists in the good dir, i.e. :
# /web/htdocs/mydomain/css/xx.css
# /web/htdocs/mydomain/js/yy.js
# /web/htdocs/mydomain/img/aa.jpg
# /web/htdocs/mydomain/img/bb.gif
# and so on...
RewriteCond %{DOCUMENT_ROOT}/%{ENV:EXT}%{REQUEST_FILENAME} -f
# file exists => override filename and stop:
RewriteRule ^(.+) %{DOCUMENT_ROOT}/%{ENV:EXT}%{REQUEST_FILENAME} [QSA,L]
這樣,您可以做一個非常好的組織,當涉及到一個“靜態”文件時,如果您在一開始就將上述規則放在上面,它們將被正確過濾,並且永遠不會重定向到index.php
。
因此,我的目錄結構看起來像這樣(我認為這很干凈),您可以輕松地執行相同的操作:
/web/htdocs/
|-- css
|-- js
|-- img
| `-- prettyPhoto
| |-- ...
| `-- light_square
|-- js
| `-- openid
`-- htm
如果所有非資源請求都是相當“虛擬”的URL,而沒有相應的文件,那么最好的方法是
#only if it is a request for a file that does not exist
#i.e exlcude resources css etc
RewriteCond %{REQUEST_FILENAME} !-f
#send it to index.php
RewriteRule .* index.php [L]
#send image requests to subfolder public
#if you can modify original resource urls to point to subfolder, this will not be necessary
RewriteRule /public/(.*)$ /subfolder/public/$1 [L]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.