2016-05-31 62 views
0

我有以下情形:mod_rewrite的省略HTML擴展循環

兩個frontcontrollers在web目錄(文檔根目錄):

web/frontend.php # handles all *.html requests 
web/backend.php # direct calls only 

重寫容易至今:

RewriteCond %{REQUEST_URI} !^/backend.php 
RewriteRule (.+)\.html$ /frontend.php [L] 

所以現在當我打電話給example.org/backend.php時,我在後端,沒有什麼特別的事情發生。當我打電話給example.org/example.org/team/john.html時,它由frontend.php處理。

到目前爲止!

現在我想要省略* .html擴展名的可能性,以便example.org/team/john在內部處理爲example.org/team/john.html

RewriteCond %{REQUEST_FILENAME}.html -f 
RewriteRule !.*\.html$ %{REQUEST_URI}.html [L] 

最後但並非最不重要我想請求重定向到john.htmljohn,以避免重複的內容。

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} -f 
RewriteCond %{REQUEST_URI} ^(.+)\.html$ 
RewriteRule (.*)\.html$ /$1 [R=301,L] 

每一個部分都工作在它自己的,但放在一起,我得到一個循環,這並不讓我感到吃驚,但我不知道該如何避免這種情況。我搜查了文檔,嘗試了幾個旗幟和條件,但我完全陷入困境,我需要幫助。

這裏是整個.htaccess文件:

<IfModule mod_rewrite.c> 
    RewriteEngine on 
    RewriteBase/

    # extend html extension internally 
    RewriteCond %{REQUEST_FILENAME}.html -f 
    RewriteRule !.*\.html$ %{REQUEST_URI}.html [L] 

    # redirect example.html to example 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} -f 
    RewriteCond %{REQUEST_URI} ^(.+)\.html$ 
    RewriteRule (.*)\.html$ /$1 [R=301,L] 

    # frontcontroller 
    RewriteCond %{REQUEST_URI} !^/backend.php 
    RewriteRule (.+)\.html$ /frontend.php [L] 
</IfModule> 

任何幫助將是巨大的。

回答

1

爲了避免一個循環,你可以使用THE_REQUEST

RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} -f 
    RewriteCond %{THE_REQUEST} "\.html " 
    RewriteRule ^(.*)\.html$ /$1 [R,L] 

無關,但你可以簡化你的規則。第一個

RewriteCond %{REQUEST_URI} !^/backend.php 
RewriteRule (.+)\.html$ /frontend.php [L] 

您已經檢查(.+)\.html,這樣你就可以省略RewriteCond。接下來,您不使用捕獲部分(.+)。將其替換爲.以確保它不是空的。那麼這給

RewriteRule .\.html$ /frontend.php [L] 

第二個,除非你有你的網站*.html.html文件,你並不需要檢查!html並且可以只使用^RewriteRule模式

RewriteCond %{REQUEST_FILENAME}.html -f 
RewriteRule^%{REQUEST_URI}.html [L] 
+0

太棒了!謝謝! –

1

環路是因爲多個內部重定向的,您可以使用END標誌,以防止重寫循環

RewriteRule ^(.+)\.html$ /$1 [L,R=301] 
RewriteCond %{REQUEST_FILENAME}.html -f 
RewriteRule !.*\.html$ %{REQUEST_URI}.html [END] 
+0

好,見效快,很有幫助。謝謝!但我標記了olafs爲額外努力的答案。 –