2012-02-12 35 views
-1

我試圖在我的.htaccess文件中使用mod_rewrite來清理我的URL。如何將file.php重定向到文件,但使文件指向file.php?

比方說,我有我的服務器上的以下文件:

/about.php 
/contact.php 

如果用戶鍵入aboutcontact,我想about.phpcontact.php要顯示給用戶,但確保網址保持不變(即它都發生在服務器端)。同樣,如果用戶輸入about.phpcontact.php,我希望它301重定向到aboutcontact,然後它將拉頁面服務器端,同時保持一個漂亮的URL。

我迄今爲止嘗試:

RewriteEngine on 
RewriteRule about about.php 
RewriteRule contact contact.php 
RewriteRule about.php about [R] 
RewriteRule contact.php contact [R] 

,結果在一個圓形的重定向循環。

而且反過來:

RewriteEngine on 
RewriteRule about.php about [R] 
RewriteRule contact.php contact [R] 
RewriteRule about about.php 
RewriteRule contact contact.php 

這是功能性的,但重定向不能正常工作(網址保持不變)。

我該怎麼做才能讓我沒有重定向循環,但是我的頁面都會指向沒有.php的版本?

注:我知道[R]是302不是301,但我使用302進行測試。

+1

不是一個真正的PHP問題 - 但請記住爲您的重定向輸入分隔符,即。^about/$否則所有與'about'有關的東西都會重定向到about.php(例如about/xyz /將重定向到about.php)。另外發現你想把'/ about /'重定向到'about.php'有點奇怪,但是你也想把'about.php'重定向到'/ about /' - 好像只是繞着圈子走。 .. – MrJ 2012-02-12 16:21:30

+0

@MrJ我不想將'/ about'重定向到'/ about.php' - 我想讓apache簡單地顯示'about.php'作爲'about' – 2012-02-12 16:24:53

+1

他們希望當你瀏覽到/ about/about.php腳本在沒有轉發的情況下執行。除了不讓他們直接瀏覽到about.php – 2012-02-12 16:30:18

回答

1
RewriteEngine on 

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

RewriteRule ^tech$ tech.php [L] 
RewriteRule ^contact$ contact.php [L] 
RewriteRule ^tech\.php$ tech [L,R] 
RewriteRule ^contact\.php$ contact [L,R] 
+0

這適用於'/ contact'(顯示正確的頁面),但如果我去'/ contact.php',我沒有被重定向到'/ contact' – 2012-02-12 16:27:29

+0

在原始解決方案中遺漏了錯誤的RegEx。現在修復它。看到上面的 – Gerben 2012-02-12 16:31:10

+0

偉大的作品! - 謝謝! – 2012-02-12 16:32:26