2010-06-21 79 views
6

我有一個網站,所有頁面都是php腳本,所以URL結束.php。使用mod_rewrite從URL末尾隱藏.php

我添加以下到.htaccess文件,現在我可以訪問.php文件不帶.php擴展名:

RewriteEngine On # Turn on rewriting 

RewriteCond %{REQUEST_FILENAME}.php -f # If the requested file with .php on the end exists 
RewriteRule ^(.*)$ $1.php # serve the PHP file 

到目前爲止好。但是現在我想在所有的.php文件上添加一個重定向,這樣我的控制之外的任何舊鏈接都會被重定向到新版本的URL。

我已經試過這樣:

RewriteEngine On # Turn on rewriting 

RewriteCond %{REQUEST_URI} .*\.php 
RewriteRule ^(.*)\.php$ http://example.com/$1 [R=permanent,L] 

RewriteCond %{REQUEST_FILENAME}.php -f # If the requested file with .php on the end exists 
RewriteRule ^(.*)$ $1.php [L] # serve the PHP file 

,但似乎發送重定向即使對於不以.php結尾的URL,讓我陷入無限循環。我嘗試的任何其他組合似乎都不匹配任何請求(並留下我在page.php)或所有請求(並讓我陷入循環)。

+1

檢出http://stackoverflow.com/questions/3024631/htaccess-remove-php-extension-index-php-and-add-trailing-slash/ – TheDeadMedic 2010-06-21 16:21:08

回答

7
RewriteEngine On 

RewriteCond %{THE_REQUEST} ^\w+\ /(.*)\.php(\?.*)?\ HTTP/ 
RewriteRule^http://%{HTTP_HOST}/%1 [R=301] 

RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule .* $0.php 

只有%{THE_REQUEST}沒有在這種情況發生在第二個規則的內部重定向改寫(%{REQUEST_URI},在另一方面,是)。

0

您重定向沒有.PHP

與.PHP頁面結束的頁面然後你的第一條規則rewites所有頁面不.php後綴名爲.php的

結束的頁面名稱結尾這就是爲什麼你必須循環:-)

+0

我已經用我的.htaccess文件重寫了這個問題充分。添加.php的規則出現在移除並重定向的規則之後。 AFAICS,RewriteCond – rjmunro 2010-06-21 16:25:27

0

添加NS到最後一條規則的參數列表

+0

有些問題我認爲這也會起作用,但似乎並不奏效。此外,對於條件'RewriteCond%{IS_SUBREQ} = false',我得到'[localhost/sid#1fd6de0] [rid#5aa2e20/initial/redir#1](4)[perdir U:/ htdocs /] RewriteCond:input ='false'pattern ='= false'=>匹配' – Artefacto 2010-06-21 16:27:21

+0

這對我不起作用。 – rjmunro 2010-06-21 16:32:14

0

您可能能夠也添加[L]到重寫規則添加.php,使其停止進程荷蘭國際集團的其他規則:

RewriteRule ^(.*)$ $1.php [L] # serve the PHP file 
+0

我試過了,沒有區別。我已將它添加到問題中的版本以保存不明確性。 – rjmunro 2010-06-21 16:18:48

0

多虧了@TheDeadMedic指針this question,我能夠通過改變找到一個解決方案,以我自己的問題:

RewriteCond %{REQUEST_URI} .*\.php 

到:

RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP 

我不明白爲什麼我的版本沒有做同樣的事情,但。

+0

看到我的答案。您的解決方案稍有不同(僅適用於GET請求)。 – Artefacto 2010-06-21 17:13:42