thinkphp 二級域名綁定模塊,導致設置的路由被多域名共用的問題解決方案


問題背景:

在router.php路由配置文件設置了二級域名和路由設置

use think\Route;
Route::domain('www','index');
Route::domain('admin','admin');
Route::domain('m','m');

Route::rule('show/:id','index/Article/item');
Route::rule('about_us','index/index/about_us');

 

遇到的問題:

訪問 www.t.com/about_us 會訪問  index/index/about_us 即index模塊index控制器的about_us方法;

但是 訪問 admin.t.com/about_us 也會訪問  index/index/about_us ;這顯然是我們不想看到的

 

解決思路:

能不能在Route的rule()中做一個判斷?如果當前域名是綁定了admin模塊的,但是設置的路由地址(即:index/index/about_us) 的模塊不是admin模塊,那么就忽略該路由設置

 

修改源碼:

    /**
     * 注冊路由規則
     * @access public
     * @param string|array $rule    路由規則
     * @param string       $route   路由地址
     * @param string       $type    請求類型
     * @param array        $option  路由參數
     * @param array        $pattern 變量規則
     * @return void
     */
    public static function rule($rule, $route = '', $type = '*', $option = [], $pattern = [])
    {
        $r_data = explode('/',$route);
        $host_data = explode('.',$_SERVER ['HTTP_HOST']);
        if(count($r_data) == 3 && count($host_data) == 3){
            $erji_host = $host_data[0];
            if(isset(self::$rules['domain'][$erji_host])){
                if(self::$rules['domain'][$erji_host]['[bind]'][0] != $r_data[0]){
                    return false;
                }
            }
        }
        $group = self::getGroup('name');

        if (!is_null($group)) {
            // 路由分組
            $option  = array_merge(self::getGroup('option'), $option);
            $pattern = array_merge(self::getGroup('pattern'), $pattern);
        }

        $type = strtolower($type);

        if (strpos($type, '|')) {
            $option['method'] = $type;
            $type             = '*';
        }
        if (is_array($rule) && empty($route)) {
            foreach ($rule as $key => $val) {
                if (is_numeric($key)) {
                    $key = array_shift($val);
                }
                if (is_array($val)) {
                    $route    = $val[0];
                    $option1  = array_merge($option, $val[1]);
                    $pattern1 = array_merge($pattern, isset($val[2]) ? $val[2] : []);
                } else {
                    $option1  = null;
                    $pattern1 = null;
                    $route    = $val;
                }
                self::setRule($key, $route, $type, !is_null($option1) ? $option1 : $option, !is_null($pattern1) ? $pattern1 : $pattern, $group);
            }
        } else {
            self::setRule($rule, $route, $type, $option, $pattern, $group);
        }

    }

 

2019 11-13 07點36分:此方法並不好,在Route里面,判斷前綴是m,index還是admin,然后在判斷里面設置Route::set。。。更好


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM