I have a setup where I allow users to choose a subdomain or to add their own custom domain names. The problem is that some of my routes "clash". One of those being the /
route.
First, I added a domain group around all base routes that filtered out only my domain name. Here is that version:
// Base routes
Route::domain(config('app.domain')->group(function () {
Route::get('/', 'HomeController')->name('home');
});
// Profile routes
Route::domain('{profileUrl}')->group(function () {
Route::get('/', 'UserController@show')->name('users.show');
});
But then the base routes doesn't match www.domain.com
. Which made me think that I should somehow use regex to exclude the domain + www
from the profile routes. Meaning, the base routes would act as a fallback. So I changed my routes to this:
// Profile routes
Route::domain('{profileUrl}')->group(function () {
Route::get('/', 'UserController@show')->name('users.show');
});
// Base routes
Route::get('/', 'HomeController')->name('home');
And tried excluding routes by registering a pattern like this:
\Route::pattern('profileUrl', '^(?!(domain\.com|www\.domain\.com)$).*');
But since the Laravel router uses Str::is()
to match patterns, the regex doesn't work.
I am aware of that I could solve this using nginx, but that would require configuring all prod + staging + dev servers even more. I rather have that in my codebase.
How do I match all requests but main domain and www subdomain in a Laravel router group?