Created
April 22, 2024 12:00
-
-
Save 4lun/48ff0c9703e69fb34e4d671e80104684 to your computer and use it in GitHub Desktop.
Laravel Route macros/helpers for serving multiple domains
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\Route; | |
// Usage: | |
// | |
// Route::domain('domain.com', function () { | |
// Route::get('/', [DomainController::class, 'index']); | |
// }); | |
// | |
// Route::redirectDomain('www.'.$domain, $domain); // e.g. redirect to non-www | |
Route::macro('redirectDomain', function (string $from, string $to) { | |
Route::group(['domain' => $from], function () use ($to) { | |
Route::get('/{any}', function (Request $request) use ($to) { | |
$fullHost = $request->schemeAndHttpHost(); | |
$fullUrl = $request->fullUrl(); | |
if (strpos($fullUrl, $fullHost) === 0) { | |
$fullPath = substr($fullUrl, strlen($fullHost)); | |
return redirect("https://{$to}{$fullPath}"); | |
} | |
return redirect("https://{$to}"); | |
})->where('any', '.*'); | |
}); | |
}); | |
Route::macro('domain', function (string|array $domain, \Closure $definition) { | |
foreach ((array) $domain as $domain) { | |
Route::group(['domain' => $domain], $definition); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment