简体   繁体   中英

Creating a route in Laravel using subdomain and domain wildcards

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM