使用Laravel 5.2,我想设置一个通配符子域组,这样我就可以捕获参数。我试过这个:
Route::group(['middleware' => ['header', 'web']], function () {
Route::group(['domain' => '{alias}.'], function () {
Route::get('alias', function($alias){
return 'Alias=' . $alias;
});
});
});
我也试过['domain' => '{alias}.*']
。
我调用这个URL:http://abc.localhost:8000/alias
,它返回一个未找到路由的错误。
我的本地环境是使用php artisan serve
命令的localhost:8000
。是否可以在没有实际域名关联的情况下在本地进行设置?
我以前也有类似的任务。如果你想捕获任何域,任何格式-不幸的是,你不能直接在路由文件中完成。Routes文件要求URL的至少一部分是预定义的、静态的。
我最终做的是创建一个中间件,解析域URL并在此基础上执行一些逻辑,例如:
class DomainCheck
{
/**
* Handle an incoming request.
*
* @param 'Illuminate'Http'Request $request
* @param 'Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$domain = parse_url($request->url(), PHP_URL_HOST);
// Remove www prefix if necessary
if (strpos($domain, 'www.') === 0) $domain = substr($domain, 4);
// In my case, I had a list of pre-defined, supported domains
foreach(Config::get('app.clients') as $client) {
if (in_array($domain, $client['domains'])) {
// From now on, every controller will be able to access
// current domain and its settings via $request object
$request->client = $client;
return $next($request);
}
}
abort(404);
}
}
在第2行,您有:
Route::group(['domain' => '{alias}.'], function() {
替换为以下内容:
Route::group(['domain' => '{alias}.localhost'], function() {
在那之后它应该会起作用。