Creating a route in Laravel using subdomain and domain wildcards

偶尔善良 提交于 2019-12-12 00:08:01

问题


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

I also tried ['domain' => '{alias}.*'].

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

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?


回答1:


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.

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



回答2:


On line 2 where you have:

Route::group(['domain' => '{alias}.'], function() {

Replace it with the following:

Route::group(['domain' => '{alias}.localhost'], function() {

It should work after that.



来源:https://stackoverflow.com/questions/37286892/creating-a-route-in-laravel-using-subdomain-and-domain-wildcards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!