Skip to content

Instantly share code, notes, and snippets.

@4lun
Created April 22, 2024 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 4lun/48ff0c9703e69fb34e4d671e80104684 to your computer and use it in GitHub Desktop.
Save 4lun/48ff0c9703e69fb34e4d671e80104684 to your computer and use it in GitHub Desktop.
Laravel Route macros/helpers for serving multiple domains
<?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