2011-09-12 46 views
1

我試圖從我的PHP頁面做出漂亮,友好的URL,但是我一直運行到500內部錯誤,所以我卡住了。這裏的破敗:重寫/重定向關於擴展和斜槓的問題

文件夾結構

/ 
    /index.php 
     /about  <--Folder 
     /about/index.php 
     /about/our-people.php <--a subpage 
     /services <--Another folder 
     /services/index.php 
     /services/service1.php <--another subpage 

我希望它是,這樣的URL沒有.php擴展名,但包含代替結尾的斜線。例如,「我們的人員」頁面將爲www.example.com/about/our-people/

www.example.com/about/our-people.php或www.example.com/about /我們的人(沒有尾隨斜線)將去www.example.com/about/our-people/

我知道這個問題可能已被要求死亡,但我已經嘗試了很多來自Stackoverflow和其他地方的例子。 Apache對我來說就像伏都教,有時它會做一些神奇的事情,有時它不起作用。這是我到目前爲止的代碼:

#add www to non-www 
RewriteCond %{HTTP_HOST} ^example.com [NC] 
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301] 

#Remove .PHP 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php [L] 

#Add Slash 
RewriteCond %{REQUEST_URI} !(.*)/$ 
RewriteRule ^(.*)$ http://www.example.com/$1/ [L,R=301] 
+0

只是一個評論;尾部的斜槓表示子內容,而斜槓通常不是前一個標記的子項。如果你真的認爲你所看到的資源是我們的人,那麼它可能應該是www.example.com/about/our-people,我敢打賭我的靴子,這個斜線重寫是你的主要罪魁禍首。 – AlexanderJohannesen

+0

現在,當我輸入www.example.com/about/our-people/時,上面的代碼給了我一個內部服務器錯誤,但是這個頁面對於www.example/about/our-people和www.example/about /我們的people.php ...但是我不希望它做到這一點,我想它到第一個網址! –

+0

:)是的,我明白這就是你想要的,我只是說可能這不是最明智的(也不是最具語義意義)的事情。 – AlexanderJohannesen

回答

0

我會對此有一點不同。如果您對Apache不太熟悉,那麼我建議您儘可能多地從Apache中承擔責任,並設置一個「調度程序」腳本,通過檢查請求的URI來決定執行哪個PHP文件。

這個想法很簡單:將每個請求「重定向到」一個 PHP文件,然後使用該文件來確定您實際想要執行的文件。

例如

http://domain.com/ =>的index.php?請求=

http://domain.com/moo/ =>的index.php?請求=も/

http://domain.com/moo/1/2/3/4/ =>的index.php?請求=も/ 1/2/3/4/

等等

例子:

(這是假設你在你的Web根目錄的.htaccess和index.php的文件)

的.htaccess:

# "Hi Apache, we're going to be rewriting requests now!" 
# (You can do all this in Apache configuration files too, of course) 
RewriteEngine On 
RewriteBase/

# Ignore *.gif, *.jpg. *.png, *.js, and *.css requests, so those files 
# will continue to be served as per usual 
RewriteRule \.(gif|jpg|png|js|css)$ - [L] 

# For the rest, convert the URI into $_GET[ 'request' ] 
RewriteRule ^(.*)$ index.php?request=$1 [QSA] [L] 

的index.php:

<?php 

print "<pre>Request: " . $_GET[ 'request' ] . "\n"; 

// Dispatcher should be smarter than this -- otherwise you 
// will have serious security concerns 

$filename = $_GET[ 'request' ] . '.php'; 

if(file_exists($filename) === TRUE) 
    require($filename); 
else 
    print "Not found: $filename";