我正在尝试为一些特定的变量子域进行经过身份验证的子域路由:
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' => 'Controller@dashboard']);
// ...various other backend routes...
});
// Frontend routes
Route::auth();
Route::get('/', function () {
return view('frontend');
});
});
当我访问任何路由时,我可以追踪到subdomain
中间件没有任何内容......它只是路由到404页面。
我如何在Laravel 5.2中完成这项工作?
答案 0 :(得分: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
内,我添加了此内容以处理来自app.example.com
的{{1}}的重定向,即使前缀为example.com
或staging
:
testing
routes.php的新内容:
public function redirectPath()
{
if (\Auth::check()) {
return redirect()->intended(static::getAppUrl())->getTargetUrl();
} else {
return $this->redirectTo;
}
}
希望如果有人尝试类似的话,这会有所帮助!