84669 人學習
152542 人學習
20005 人學習
5487 人學習
7821 人學習
359900 人學習
3350 人學習
180660 人學習
48569 人學習
18603 人學習
40936 人學習
1549 人學習
1183 人學習
32909 人學習
我知道您可以在 htaccess 中添加規則,但我發現 PHP 框架不會這樣做,並且不知何故您仍然擁有漂亮的 URL。如果伺服器不知道 URL 規則,他們如何做到這一點?
我一直在尋找 Yii 的 url 管理器類,但我不明白它是如何做到的。
這通常是透過將所有請求路由到單一入口點(根據請求執行不同程式碼的檔案)來完成的,規則如下:
# Redirect everything that doesn't match a directory or file to index.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .* index.php [L]
然後,該檔案將請求($_SERVER["REQUEST_URI"]) 與路由清單進行比較- 與請求匹配的模式到控制器操作(在MVC 應用程式中)或其他操作的映射執行路徑。框架通常包含一個可以從請求本身推斷控制器和操作的路由,作為備份路由。
$_SERVER["REQUEST_URI"]
一個簡單的小例子:
'Home', '/about' => 'About' ); // Match the request to a route (find the first matching URL in routes) $request = '/' . trim($_SERVER['REQUEST_URI'], '/'); $route = null; foreach ($routes as $pattern => $class) { if ($pattern == $request) { $route = $class; break; } } // If no route matched, or class for route not found (404) if (is_null($route) || !class_exists($route)) { header('HTTP/1.1 404 Not Found'); echo 'Page not found'; exit(1); } // If method not found in action class, send a 405 (e.g. Home::POST()) if (!method_exists($route, $_SERVER["REQUEST_METHOD"])) { header('HTTP/1.1 405 Method not allowed'); echo 'Method not allowed'; exit(1); } // Otherwise, return the result of the action $action = new $route; $result = call_user_func(array($action, $_SERVER["REQUEST_METHOD"])); echo $result;
與第一個配置結合,這是一個簡單的腳本,允許您使用像 domain.com/about 這樣的 URL。希望這可以幫助您了解這裡發生的事情。
domain.com/about
這通常是透過將所有請求路由到單一入口點(根據請求執行不同程式碼的檔案)來完成的,規則如下:
然後,該檔案將請求(
$_SERVER["REQUEST_URI"]
) 與路由清單進行比較- 與請求匹配的模式到控制器操作(在MVC 應用程式中)或其他操作的映射執行路徑。框架通常包含一個可以從請求本身推斷控制器和操作的路由,作為備份路由。一個簡單的小例子:
與第一個配置結合,這是一個簡單的腳本,允許您使用像
domain.com/about
這樣的 URL。希望這可以幫助您了解這裡發生的事情。