使用子域和域通配符在Laravel中创建路由 [英] Creating a route in Laravel using subdomain and domain wildcards

查看:83
本文介绍了使用子域和域通配符在Laravel中创建路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Laravel 5.2,我想设置一个通配符子域组,以便捕获参数.我试过了:

With Laravel 5.2, I would like to set up a wildcard subdomain group so that I can capture a parameter. I tried this:

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,它返回未找到路由的错误.

I'm calling this URL: http://abc.localhost:8000/alias and it returns an error of route not found.

使用php artisan serve命令,我的本地环境是localhost:8000.可以在没有关联实际域名的情况下在本地进行设置吗?

My local environment is localhost:8000 using the php artisan serve command. Is it possible to set this up locally without an actual domain name associated to it?

推荐答案

我之前也有类似的任务.如果要捕获任何域,任何格式-不幸的是,您不能直接在路由文件中进行捕获.路由文件期望URL的至少一部分是预定义的,静态的.

I had a similar task before. If you want to catch any domain, any format - unfortunately you cannot do it directly in the routes file. Routes file expects at least one portion of the URL to be pre-defined, static.

我最终要做的是创建一个中间件来解析域URL,并基于该中间件执行一些逻辑,例如:

What I ended up doing, is creating a middleware that parses domain URL and does some logic based on that, eg:

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);
    }
}

这篇关于使用子域和域通配符在Laravel中创建路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆