Laravel Route Group Applies to Entire Domain

I would like to be able to use different routes in my application for different domains. I would like to act differently depending on whether the domain is

  • My own domain, for example. mysite.com/something
  • A subdomain of my domain, for example. subdomain.mysite.com/something
  • Any other domain, for example. anotherdomain.com

I approached such a problem:

// Match my own domain
Route::group(['domain' => 'mysite.com'], function()
{
    Route::any('/', function()
    {
        return 'My own domain';
    });
});

// Match a subdomain of my domain
Route::group(['domain' => '{subdomain}.mysite.com'], function()
{
    Route::any('/', function($subdomain)
    {
        return 'Subdomain ' . $subdomain;
    });
});

// Match any other domains
Route::group(['domain' => '{domain}'], function()
{
    Route::any('/', function()
    {
        return 'Full domain ';// . $domain;
    });
});

The first two groups work fine. Visits mysite.comdisplays My own domainand visits are subdomain.mysite.comdisplayed Subdomain subdomainas expected. However, when I visit using anotherdomain.com(I have it configured as an alias in my vhost file and also points to the loopback IP address in my hosts file), I get NotFoundHttpException:

/var/www/portfolio/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php

the code:

    $others = $this->checkForAlternateVerbs($request);

    if (count($others) > 0)
    {
        return $this->getOtherMethodsRoute($request, $others);
    }

    throw new NotFoundHttpException;
}

, , ? , - , , $subdomain.

,

+4
4

...

, ,

// Match my own domain
Route::group(['domain' => 'mysite.com'], function()
{
    Route::any('/', function()
    {
        return 'My own domain';
    });
});

// Match a subdomain of my domain
Route::group(['domain' => '{subdomain}.mysite.com'], function()
{
    Route::any('/', function($subdomain)
    {
        return 'Subdomain ' . $subdomain;
    });
});

// Match any other domains
Route::group(['domain' => '{domain}.{tld}'], function(){

    Route::any('/', function($domain, $tld){
        return 'Domain: ' . $domain . '.' . $tld;
    });
});

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

    Route::any('/', function($sub, $domain, $tld){
        return 'subdomain: ' . $sub . '.' . $domain . '.' . $tld;
    });
});

, , HOSTS 127.0.0.1: -)

+6

, , config/app.php.

.

, Laravel .

0

, , . Laravel , , . , , , .

- , , boot app/Providers/RouteServiceProvider.php :

public function boot(Router $router)
{
    $router->pattern('domain', '[a-z0-9.]+');
    parent::boot($router);
}

.

0

, . :

,

Route::any('/', function()
{
    return 'Full domain ';// . $domain;
});
-1
source

All Articles