2016-09-20 145 views
2

我試圖得到驗證的子域路由對於一些特定變量子站點:Laravel認證的動態路由子域

app.example.com 
staging.app.example.com 
testing.app.example.com 

這些應該由AUTH中間件把守。它們基本上都參考app.example.com,但對於不同的環境。擊中這些領域

一切都應該去來賓路線:

example.com 
staging.example.com 
testing.example.com 

這是我到目前爲止已經試過......

創造了這個中間件,以防止子域參數從搞亂其他路線,並允許成功驗證重定向到app.example.com

class Subdomain 
{ 
    /** 
    * Handle an incoming request. 
    * 
    * @param \Illuminate\Http\Request $request 
    * @param \Closure $next 
    * @return mixed 
    */ 
    public function handle($request, Closure $next) 
    { 
     $route = $request->route(); 
     $subdomain = $route->parameter('subdomain'); 

     if (!empty($subdomain) && preg_match('/^(staging|testing)\.(app.\)?/', $subdomain, $m)) { 
      \Session::put('subdomain', $m[1]); 
     } 

     $route->forgetParameter('subdomain'); 

     return $next($request); 
    } 
} 

將此添加到Kernel.php:

protected $routeMiddleware = [ 
    'subdomain' => \App\Http\Middleware\Subdomain::class, 
]; 

routes.php文件的內容:

Route::group(['domain' => '{subdomain?}example.com', 'middleware' => 'subdomain'], function() { 
    // Backend routes 
    Route::group(['middleware' => 'auth'], function() { 
     Route::get('/', ['as' => 'dashboard', 'uses' => '[email protected]']); 

     // ...various other backend routes... 
    }); 

    // Frontend routes 
    Route::auth(); 
    Route::get('/', function() { 
     return view('frontend'); 
    }); 
}); 

當我訪問任何途徑,我可以跟蹤沒有命中subdomain中間件...它只是路由到404頁。

我該如何在Laravel 5.2中完成這項工作?

回答

0

由於我的設置目標是允許使用可選的環境前綴處理某些子域組,因此我採用以下方式處理它。

我放棄Subdomain類是不必要的。

我已將此添加到.env文件,以便每個環境可以有它自己的域名,以便在本地開發服務器仍然有效獨立的分期和生產服務器的:

APP_DOMAIN=example.dev 

生產和分期它僅僅是:

APP_DOMAIN=example.com 

config/app.php我說:

'domain' => env('APP_DOMAIN', null), 

我添加了這些方法\App\Http\Controllers\Controller

public static function getAppDomain() 
{ 
     return (!in_array(\App::environment(), ['local', 'production']) ? \App::environment() . '.' : '') . 'app.' . config('app.domain'); 
} 

public static function getAppUrl($path = '', $secure = false) 
{ 
    return ($secure ? 'https' : 'http') . '://' . static::getAppDomain() . ($path ? '/' . $path : ''); 
} 

Auth\AuthController.php我從example.com將此添加到處理重定向到app.example.com即使前綴stagingtesting

public function redirectPath() 
{ 
    if (\Auth::check()) { 
     return redirect()->intended(static::getAppUrl())->getTargetUrl(); 
    } else { 
     return $this->redirectTo; 
    } 
} 

routes.php文件的新內容:

// Backend routes 
Route::group(['domain' => Controller::getAppDomain(), 'middleware' => 'auth'], function() { 
     Route::get('/', ['as' => 'dashboard', 'uses' => '[email protected]']); 

     // ...various other backend routes... 
}); 

// Frontend routes 
Route::auth(); 
Route::get('/', function() { 
     return view('frontend'); 
}); 

希望這有助於任何人嘗試類似的!