2012-10-22 35 views
2

我在我的htdocs .htaccess文件/ MVC /文件夾,看起來像這樣htaccess中的mod_rewrite:防止循環的最好方法?

RewriteEngine On 

# if its already been rewritten to the specific folder 
RewriteCond %{REQUEST_URI} ^/MVC/public/img/(.*)$ [OR] 
RewriteCond %{REQUEST_URI} ^/MVC/public/index.php$ 
# skip next two rules 
RewriteRule .? - [S=2] 

# rewrite image requests 
RewriteRule (.*\.(jpg|png|gif))$ public/img/$1 [L] 
# rewrite all other requests to the front controller index.php 
RewriteRule (.*) public/index.php?url=$1 [QSA,L] 

我想實現的是將文件夾MVC /公/ IMG所有其他請求將所有圖像請求MVC/public文件夾中的前端控制器index.php。這是設置這些規則並防止mod_rewrite循環的最佳方式嗎?

回答

4

使用S標誌跳過是好的,但不足之處是:

  1. 這是一個有點難以閱讀(如果別人是看它)
  2. 如果需要追加新的規則,你需要檢查的方式,跳過
  3. 如果您的規則變得越來越複雜,它變得越來越難以維持預防的正確跳過

其他可能的方法循環:

RewriteCond %{ENV:REDIRECT_STATUS} 200 
RewriteRule^- [L] 

在你的規則最頂部把這個會立即完全停止重寫,如果在以前的循環應用的規則(或者是應用了mod_alias中重定向)。

所以它會是這樣的:

RewriteCond %{ENV:REDIRECT_STATUS} 200 
RewriteRule^- [L] 

# rewrite image requests 
RewriteRule (.*\.(jpg|png|gif))$ public/img/$1 [L] 
# rewrite all other requests to the front controller index.php 
RewriteRule (.*) public/index.php?url=$1 [QSA,L] 

優點:你永遠不用擔心循環,因爲第二次左右瞬間與ENV檢查 缺點結束:如果你碰巧需要創建一個規則循環,這種方法將阻止它永遠工作

+0

感謝您的幫助和解釋。奇蹟般有效。我同意你所說的'S'國旗。關於ENV:REDIRECT_STATUS,是否有這些環境變量的清單和很好的解釋? – Dalai