Home > Net >  Laravel Route Domain - skip some domain
Laravel Route Domain - skip some domain

Time:01-20

Hi

My application has to work with several domains. But I need certain routers to be ignored by ONE specific domain (base.domain).

As a result, the routers must work with different domains than the base.domain

Help please, spent a lot of time and could not do it.

// this code doesn't need to work with "base.domain"

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

 //some routes

});

if the domain will be "base.domain" - these are the routers you should ignore and use the other ones.

I tried using middleware instead of the Route::domain, but it's fail :(

CodePudding user response:

You can do this via middleware, create a subdomain middleware for route group and check for base domain in middleware and restrict to proceed further, something like below:

In your routes/web.php

Route::middleware(['subdomain'])->group(function(){
     //some routes for subdomains only..
});

Create a new middleware in your app and define in $routeMiddleware under app/Http/Kernel.php

In app/Http/Middleware/Subdomain.php

public function handle($request, Closure $next){
    if($_SERVER['HTTP_HOST'] == config('app.base_domain')){
        // redirect to base domain 
        return redirect(config('app.base_domain'));
        
        //Or your can abort the request 404
        abort(404,'Not Found');

    }
    return $next($request);
}

Define base_domain variable in your config/app.php

That's it!

CodePudding user response:

If you want to skip some specific domains you can use the where method in your route group and exclude the specific domains you want to skip.

Route::middleware(['web'])
    ->namespace($this->namespace)
    ->group(base_path('routes/web.php'));

Route::middleware(['web'])
    ->namespace($this->namespace)
    ->where('domain', '!=', 'example.com')
    ->group(base_path('routes/web.php'));

This will exclude the routes in the specified file from matching if the domain is 'example.com'

Alternatively, you can use custom middleware to check the domain and return a response if it matches a certain value.

class SkipSpecificDomains
{
    public function handle($request, Closure $next)
    {
        if ($request->getHost() === 'example.com') {
            return response('Not Allowed', 403);
        }

        return $next($request);
    }
}

Then you can apply this middleware to specific routes or groups of routes

Route::middleware(['web', SkipSpecificDomains::class])
    ->namespace($this->namespace)
    ->group(base_path('routes/web.php'));

This will check the domain of the current request and return a "Not Allowed" response with a 403 status code if it matches 'example.com'.

  • Related