Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jawsh's avatar

Subdomain routing without knowing the domain

My application is being built to run on any number of servers.

The main application is to run on www or no subdomain.

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

And I want an API to be on the subdomain api.

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

This works, but it passes {domain} and {tld} as a parameter into all of my controllers, which breaks the entire application. I can't specify the URL directly, because that breaks it on any website running the software that isn't me.

How do I have wildcards or a URL pattern for the domain tag?

0 likes
5 replies
pmall's avatar

Isnt this working :

Route::group(['domain' => 'api.*.*'], function () {
    
});
pmall's avatar
pmall
Best Answer
Level 56

Otherwise :

Route::group(['domain' => 'api.{domain}.{tld}', 'middleware' => 'domain'], function () {
    
});
class DomainMiddleware
{
    // ... 

    public function handle (Request $request, $next) {

        $request->route()->forgetParameter('domain');
        $request->route()->forgetParameter('tld');

    }

    // ... 
}
1 like
Jawsh's avatar

@pmall The middleware solution was spot on. I really wish i knew as much as you did. My life would be a lot easier.

pmall's avatar

You are welcome :) I'm surprised the first one doesnt work.

Jawsh's avatar

Me too. It was the first thing I tried.

Please or to participate in this conversation.