2016-05-31 64 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为额外努力的答案。 –