2012-05-16 28 views
1

我有一個FrontController期待2個$_GET PARAMS:

controller 
action 

到現場一個典型的呼叫看起來像這樣:

http://foo.bar/index.php?controller=start&action=register

我想什麼做的是讓用戶通過以下網址訪問本網站:

http://foo.bar/start/register

我已經試過什麼:

<IfModule mod_rewrite.c> 
RewriteEngine On 
RewriteRule ^(.+)/(.+)$ index.php?controller=$1&action=$2 [L,QSA] 
</IfModule> 

因爲這給了我404錯誤似乎並沒有工作。

mod_rewrite本身已在服務器上啓用。

+0

本身並不是答案,但已經有很多框架。使用一個。例如Symfony2。 – PorridgeBear

+1

你在哪裏放置了重寫規則 - httpd.conf或。htaccess的?如果它在.htaccess文件中,那麼哪一個?根目錄內的文件夾或子文件夾內的某個文件夾? –

+0

.htaccess,在子文件夾中。 整個項目位於一個子文件夾中,所以真實世界的URL看起來像這樣:http://foo.bar/project – iceteea

回答

2

.htaccess你貼我的作品:

// GET /cont1/action1 

print_r($_GET); 

/* output 
Array 
(
    [controller] => cont1 
    [action] => action1 
) 
*/ 

你可能想嘗試的絕對路徑index.php,而不是相對的。

無論如何,該正則表達式將導致:

// GET /cont1/action1/arg1 

print_r($_GET); 

/* output 
Array 
(
    [controller] => cont1/action1 
    [action] => arg1 
) 
*/ 

你會更好做:

<IfModule mod_rewrite.c> 
RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.*)$ /index.php?url=$1 [QSA,L] 
</IfModule> 

,並擁有你index.php分裂的$_GET['url']成控制器,動作,ARGS等...

0

有2個部分得到這個工作。如果您正在使用PHP和Apache,則必須在您的服務器上提供重寫引擎。

在用戶文件夾將名爲.htaccess這些內容的文件:

RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule . index.php [L] 

然後你index.php可以使用REQUEST_URI服務器變量,看是什麼要求:

<?php 
$path = ltrim($_SERVER['REQUEST_URI'], '/'); 
echo $path; 
?> 

如果有人請求/start/register,然後假設所有上述代碼都在html根目錄下,$path變量將包含start/register

我會使用$path的爆炸功能,使用/作爲分隔符,並將第一個元素作爲寄存器。

重寫代碼具有處理文件名和目錄名稱的好處。