2015-09-04 60 views
1

我試圖在Apache 2.4中使用mod_rewrite來附加後綴.html來請求URI。通過追加.html後綴重寫URL

應該被重寫的URI是非常簡單的,並採取以下形式:

http://host.domain/page/

上述需要被重寫爲http://host.domain/page.html。唯一的約束是重寫邏輯必須忽略引用實際文件或目錄的URI。

到目前爲止,我想出了罰款,如果有作品重寫代碼片段沒有尾隨斜線,但是如果存在一個阿帕奇發出404及以下錯誤消息:

The requested URL /redirect:/about.html was not found on this server.

(中上述情況發生時,URI是http://localhost/about/

有人可以幫我調試嗎?爲什麼Apache預先登記/redirect:

下面是再現症狀一個非常簡單的代碼片段:

RewriteEngine on 

RewriteBase/

RewriteRule ^(.+[^/])/$ /$1 [C] 

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

# This doesn't work either. 
# RewriteRule ^about/$ /about.html [L,R=301] 

回答

1

您可以使用:

RewriteEngine on 
RewriteBase/

# strip trailing slash from non-directoies 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.+?)/$ /$1 [L,R=301] 

# make sure corresponding html file exists 
RewriteCond %{DOCUMENT_ROOT}/$1\.html -f 
RewriteRule ^(.+?)/?$ $1.html [L] 
+0

能否請您解釋一下我要去哪裏錯了上面?例如,爲什麼不鏈接第一條規則去除尾部斜槓工作? – miguelg

+1

沒有必要在你的第一條規則中使用'C'標誌,並且最好使用'RewriteCond%{DOCUMENT_ROOT}/$ 1 \ .html -f'來確保相應的html文件存在。 – anubhava