2011-01-12 76 views
4



我正在設計我的應用程序。我應該做下一件事。所有GET參數(?var = value)在mod_rewrite的幫助下應該轉換爲/ var/value。我怎樣才能做到這一點?我只有1個.php文件(index.php),因爲我正在使用FrontController模式。你能幫我用這個mod_rewrite規則嗎?

對不起,我的英語。先謝謝你。PHP的所有GET參數與mod_rewrite

+4

這聽起來對您和您的用戶都很可怕。通常,使路徑看起來像指定內容是個不錯的主意,但只保留其他參數。例如,您可能不是/content.php?id=5,而是/ content/5。如果你有一些選擇的東西,但你可能想要做一些像/ content/5?opt1 = something&opt2 = something。 – Brad 2011-01-12 21:06:28

回答

6

我在使用'seo-friendly'網址的網站上做這樣的事情。

在.htaccess:

Options +FollowSymLinks 
RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule .* /index.php [L] 

然後在index.php文件:

if ($_SERVER['REQUEST_URI']=="/home") { 
    include ("home.php"); 
} 

的的.htaccess規則告訴它加載的index.php,如果要求的文件或目錄未找到。然後你只需解析請求URI來決定index.php應該做什麼。

+0

美麗。這正是我需要的。 – Qix 2013-05-01 16:09:27

1

AFAIK mod_rewrite在問號後不處理參數 - 重寫規則的regexp行結束符與'?'之前的路徑末尾相匹配。所以,你幾乎不能傳遞參數,或者在重寫時完全放棄參數。

3

的.htaccess

RewriteEngine On 

# generic: ?var=value 
# you can retrieve /something by looking at $_GET['something'] 
RewriteRule ^(.+)$ /?var=$1 

# but depending on your current links, you might 
# need to map everything out. Examples: 

# /users/1 
# to: ?p=users&userId=1 
RewriteRule ^users/([0-9]+)$ /?p=users&userId=$1 

# /articles/123/asc 
# to: ?p=articles&show=123&sort=asc 
RewriteRule ^articles/([0-9]+)/(asc|desc)$ /?p=articles&show=$1&sort=$2 

# you can add /? at the end to make a trailing slash work as well: 
# /something or /something/ 
# to: ?var=something 
RewriteRule ^(.+)/?$ /?var=$1

第一部分是接收到的URL。第二部分重寫的URL,您可以使用$_GET讀出。 ()之間的所有內容都被視爲一個變量。第一個將是$1,第二個是$2。這樣,您就可以確定變量在重寫的URL中的確切位置,從而知道如何檢索它們。

通過使用(.+),您可以保持一般性並允許「一切」。這僅僅意味着:任何字符的一個或多個(+)(.)。或者更具體而且例如僅允許數字:[0-9]+(0到9範圍內的一個或多個字符)。你可以在http://www.regular-expressions.info/找到更多有關正則表達式的信息。這是一個很好的網站來測試它們:http://gskinner.com/RegExr/

5

您的.htaccess中的以下代碼將重寫您的URL從例如。 /api?other=parameters&added=true/?api=true&other=parameters&added=true

RewriteRule ^api/   /index.php?api=true&%{QUERY_STRING} [L] 
+0

這就是我正在尋找的!謝謝! – Aaron 2013-04-13 21:13:37