2015-07-11 66 views
0

我有一個非常簡單的目標:重寫我的PHP應用程序的URL,使得localhost/slim_demo/archive被系統解釋爲localhost/slim_demo/index.php/archive,但用戶看到前者。 編輯:該系統表現得好像沒有重寫正在發生。後一版本的URL返回數據,但前者會拋出未找到錯誤。簡單的URL重寫失敗

我用下面的.htaccess文件,但它不會發生(順便說一下,作爲第二行說,在取消它拒絕所有的請求,這表明.htaccess是活蹦亂跳):

Options +FollowSymLinks -MultiViews -Indexes 
#deny from 127.0.0.1 #Uncomment to prove that .htacess is working 
RewriteEngine On 
RewriteRule ^slim_demo/(.*)$ slim_demo/index.php/$1 [NC,L] 

而且下面是從我apache2.conf相關部分:

<Directory /> 
     Options FollowSymLinks 
     AllowOverride None 
     Require all denied 
</Directory> 
<Directory /usr/share> 
     AllowOverride None 
     Require all granted 
</Directory> 
<Directory /media/common/htdocs> 
     Options Indexes FollowSymLinks 
     AllowOverride All 
     Require all granted 
</Directory> 

我也沒有a2enmod rewriteservice apache2 restart。沮喪,我也添加到了我的網站可用,做了重新啓動:

<Directory /media/common/htdocs/> 
     Options +FollowSymLinks -Indexes 
     AllowOverride All 
</Directory> 

不知道還有什麼我需要做的!

+0

哪裏是你的.htaccess在什麼位置? – Zimmi

+0

你的「slim_demo」目錄中是否有htaccess文件? –

+0

@Zimmi @Jon是的,它在'slim_demo'目錄中! – dotslash

回答

2

因此,如果這個.htaccess文件是在slim_demo目錄,您RewriteRule永遠不匹配:

在目錄和htaccess的背景下,格局將初步 匹配對文件系統路徑,去掉前綴後 將服務器引導至當前的RewriteRule

(該模式在您的情況下是^slim_demo/(.*)$部分)。

這意味着當您嘗試獲取URL localhost/slim_demo/archiveslim_demo部分被刪除,並且您的規則永遠無法匹配。

因此,你需要:

RewriteRule ^(.*)$ index.php/$1 

但是這會給你帶來無限循環和一個500錯誤。只有在REQUEST_URI沒有index.php時,您才必須觸發此規則。

所有在一起就變成了:

RewriteEngine On 
RewriteCond %{REQUEST_URI} ^(?!/slim_demo/index\.php).*$ 
RewriteRule ^(.*)$ index.php/$1 [NC,L,QSA] 
+0

它的工作原理!除了我還不明白如何。讓我讀一讀評論中的一些小問題? :) – dotslash

+0

我很抱歉,爲什麼'RewriteRule ^(。*)$ index.php/$ 1'會導致無限循環?是否因爲規則說「將所有內容重定向到index.php之後」,這意味着將「index.php/page_requested」重定向到index.php等等? – dotslash

+0

@dotslash要了解這一點,最好在[關於標誌L的Apache文檔]中解釋(https://httpd.apache.org/docs/2.2/en/rewrite/flags.html#flag_l)。當您更改URL時,Apache的工作將再次以新的URL開始,並且如果再次遇到.htaccess,它將再次運行。然後你會有一個無限循環:/ slim_demo/archive => /slim_demo/index.php/archive=> /slim_demo/index.php/index.php/archive => etc ...如果你使用的是Apache v2.4 ,有一個新的標誌'END'來處理這種問題:https://httpd.apache.org/docs/2.4/en/rewrite/flags。html#flag_end – Zimmi