Yii框架url美化

url美化

目的:

http://localtest/yii/web/index.php?r=hello/index

美化成:

http://localtest/yii/web/hello/index

這裏我是用的wampserver新建了一個localtest站點(詳情可點擊這裏點擊這裏),並將yii的basic文件夾重新命名爲yii。

對比上面的兩個地址,其實就是把index.php?r=隱藏。

這裏分兩步:

1、增加.htaccess文件

在web根目錄下增加.htaccess文件,內容爲:

RewriteEngine on

 # 如果是一個目錄或者文件,就訪問目錄或文件
 RewriteCond %{REQUEST_FILENAME} !-d

 # 如果文件存在,就直接訪問文件,不進行下面的RewriteRule
 RewriteCond %{REQUEST_FILENAME} !-f

 RewriteRule . Index.php

無法直接創建.htaccess,可以先創建一個txt文件,然後另存爲…,保存爲文件名爲.htaccess,保存類型選擇所有文件即可。

2、配置config/web.php

在config/web.php中的components數組中增加這一項:

'urlManager' => [
            // //開啓url美化
            'enablePrettyUrl' => true,
            // //隱藏index.php
            'showScriptName' => false,
            // //禁用嚴格匹配模式
            'enableStrictParsing' => false,
            // //url後綴名稱
            // 'suffix'=>'.html',
            'rules' => [
            ],
        ],

這時,可以將URL中的index.php?r=刪除,如果出現404報錯,可以查看服務器的配置,我用的是wampsever中集成的apache,需要檢查一下配置:

conf\httpd.conf中,開啓 apache 的 mod_rewrite 模塊
去掉LoadModule rewrite_module modules/mod_rewrite.so前的“#”符號;

然後修改 apache 的 AllowOverride
將 AllowOverride None 修改爲 AllowOverride All;

由於我是在conf\extra\httpd-vhosts.conf中配置了站點,所以需要同步去httpd-vhosts.conf中將對應站點的AllowOverride None 修改爲 AllowOverride All;

至此,我就可以用http://localtest/yii/web/hello/index
來訪問http://localtest/yii/web/index.php?r=hello/index

適配ajax請求路徑

由於我用Yii框架主要進行一些服務端的邏輯處理,例如接口以及session管理等,由於要做到前後端分離,Yii主要還是給前端提供API。這裏我先寫一個簡單的例子測試一下上面美化之後的url是否適用於我們常用的ajax。

先在web目錄下新建了一個index.html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>text</title>
</head>
<body>
    <h1>test</h1>
</body>
<script type="text/javascript" src="lib/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
$(function(){
    $.ajax(
            {
                type : 'GET',
                url : 'hello/resp',
                data: {
                    age: 12,
                    name: 'sean'
                },
                success : function(response){
                    console.log(JSON.parse(response) );

                }
            });
});
</script>
</html>

爲了方便,這裏我就直接引用了jquery封裝好的ajax方法,可以注意到,我這裏用的url : ‘hello/resp’。

對應的在HelloController中加了這麼個方法:

public function actionResp(Type $var = null)
    {
        $request =  Yii::$app->request;
        $age = $request->get('age');
        $name = $request->get('name');

        $arr = array('age' =>$age , 'name'=>$name);
        $response = json_encode($arr);
        return $response;
    }

在瀏覽器中,可以得到正確的返回值:
這裏寫圖片描述

可以注意到url的地址爲http://localtest/yii/web/hello/resp,這其實就是我們上面美化後的地址。

爲了進一步測試相對路徑的問題,我們在web下新建了一個test文件夾,並在其中新增了一個test.html文件:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>text</title>
</head>

<body>
    <h1>test</h1>
</body>
<script type="text/javascript" src="../lib/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
    $(function () {
        $.ajax(
            {
                type: 'GET',
                url: 'hello/resp',
                data: {
                    age: 12,
                    name: 'sean'
                },
                success: function (response) {
                    console.log(JSON.parse(response));

                }
            });
    });
</script>

</html>

內容與index.html一致(jquery路徑做對應的變化),瀏覽器中訪問後,ajax請求報404:
這裏寫圖片描述

可以注意到,此時ajax請求的地址爲http://localtest/yii/web/test/hello/resp的,請求是在web/test下,不是之前的web/目錄,稍微變通一下,修改一下url: '../hello/resp',再次訪問就可以了。

至此我們基本上可以知道了,通過我們的URL美化,我們可以將發送到web/下的請求,轉發到index.php中,所以需要保證我們的請求發送到了web目錄下。但是,如果按照上述的方法,每一個ajax請求都手動去計算和更改對應的url肯定是不合理的,因此可以封裝一個公共方法。

如果我們的前端代碼都是放在web目錄下,那麼可以在web下新建一個公共js文件,裏面寫一個獲取web路徑方法即可:

function getLocalUrl() {
        var url = '';
        var str =  window.location.href;
        try{
            url =  str.split('web/')[0] + 'web/';
        }catch(e){

        }
        return url;
    }

這樣,上述的test.html文件可以引入這個方法,url的方法就可以改寫成:

url: getLocalUrl() + 'hello/resp',

這樣,每次調用的時,直接調用getLocalUrl()方法即可,不需要在人爲計算路徑。

同理,如果如果前端代碼和後端php代碼分開不同路徑部署,也可以根據自己具體的項目路徑來獲取到web路徑。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章