問題描述
我目前正在研究如何使用 Mod rewrite 修改 php 中的 URL.
I am currently researching how to modify URLs in php using Mod rewrite.
典型的 URL 可能如下所示:
A typical URL could look like this:
http://www.fitness.com/find_a_pt/?county=&constituency=211&gender=&action=search
現在在上面的例子中只選擇了一個選區.未指定縣或性別.
Now in the above example only a constituency has been selected. No county or gender has been specified.
現在上述選區指的是達特福德".
Now the above constituency refers to 'Dartford'.
所以如果 URL 是這樣就好了:
So it would be good if the URL read:
http://www.fitness.com/find_a_pt/dartford
現在增加的復雜性是性別可能是:
Now the added complication is that a gender may be either:
1) 未選擇 - 根據上面的網址
1) Not selected - as per the URL above
2) 男
http://www.ego3fitness.com/find_a_pt/?county=&constituency=211&gender=1&action=search
3) 女性
http://www.ego3fitness.com/find_a_pt/?county=&constituency=211&gender=&actiom=search
因此 URL 需要讀取:
So the URLs would need to read:
1) http://www.fitness.com/find_a_pt/dartford
2) http://www.fitness.com/find_a_pt/dartford/male
3) http://www.fitness.com/find_a_pt/dartford/female
首先,URL 重寫是否可以做到這一點,如果可以,有人可以提供一個示例供我使用.
Firstly is it possible to be this specific with the URL rewrites and if so could someone provide an example for me to work from.
提前感謝您的幫助.
推薦答案
我總是使用相同的 mode_rewrite 規則:
I always use the same mode_rewrite rules:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
有了這個規則,一切都被轉發到 index.php.所以你可以自由地用 PHP 實現每一個 url 邏輯.
With this rules everything is forwared to index.php. So you are free to implement every url logic with PHP.
您可以使用 $_SERVER['REQUEST_URI']
獲取請求 uri,然后做任何您想做的事情.
You can get the request uri with $_SERVER['REQUEST_URI']
and do whatever you want.
很高興有一個帶有正則表達式規則的路由類來解析 uri.看一個例子 here 并閱讀Zend、Code Igniter 等大型框架是如何做到的.(順便說一下,我提供的重寫規則來自Zend Framework)
It is nice to have a Routing class with regex rules to parse the uri. Look at an example here and also read how the big frameworks like Zend, Code Igniter etc. do it. (The rewrite rule I provided is from Zend Framework by the way)
這篇關于在 URL 中傳遞多個值時,PHP 中的 URL 重寫的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!