首頁  >  文章  >  後端開發  >  php如何實作頁面路由轉發

php如何實作頁面路由轉發

coldplay.xixi
coldplay.xixi原創
2020-10-07 15:03:503604瀏覽

php實作頁面路由轉送的方法:先設定nginx伺服器,在【.htaccess】寫上nginx的語法;然後開啟根目錄的【index.php】,寫好檔案路由即可。

php如何實作頁面路由轉發

php實作頁面路由轉送的方法:

1、設定nginx伺服器

nginx伺服器不會自動讀取.htaccess,也不支援.htaccess語法,這裡需要做一個投機取巧的方法:在.htaccess中寫上nginx的語法,同時把該文件引入到nginx的配置中。這樣就達到了和apache同樣的目的。編輯.htaccess文件,輸入以下內容並保存

if (!-e $request_filename){
    rewrite ^(.*)$ /index.php;
}
location ~ /.ht {
    deny  all;
}

【解釋】nginx匹配失敗的uri全都轉給index.php,同時禁止訪問.htaccess文件

最重要的一步:在nginx配置中,在server{}內加入一句話:

include E:/demo/.htaccess;

【解釋】將該檔案原封不動的引入到nginx配置中。注意使用絕對路徑!

2、寫index.php路由

打開根目錄的index.php,輸入以下內容

<?php
    //路由
    $uri = $_SERVER[&#39;REQUEST_URI&#39;]; //获取uri,例如 http://www.abc.com/study,其uri="/study"
    switch($uri){
        case "/":      include "template/home.php";  break;
        case "/study": include "template/study.php"; break;
        case "/play":  include "template/play.php";  break;
    }
编写/template/下的网页文件
/template/下存放的网页文件,随便编辑点html用于测试。例如 home.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>这里是home</title>
</head>
<body>
    <h1>你好,这里是home页面</h1>
</body>
</html>

效果

在瀏覽器訪問http://localhost:8000             可以存取/template/home.php

在瀏覽器上存取http://localhost:8000/study    可以存取/template/study.php

在瀏覽器訪問http://localhost:8000/play      可以訪問/template/play.php

##相關免費學習推薦:

php程式設計(視頻)

以上是php如何實作頁面路由轉發的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn