In our Slack community, someone recently asked about serving multiple domains out of the same Laravel app. They wanted specific routes to only work for certain domains.
In the Laravel documentation, it shows an example of doing routing based on subdomains:
Route::domain('{account}.example.com')->group(function () {
Route::get('user/{id}', function (string $account, string $id) {
// ...
});
});
But would this work with a main domain instead of a subdomain? Yes! Here's an example of that:
Route::domain('example.com')->group(function () {
Route::get('article-xyz', function (string $id) {
// this route will only work on example.com
// other.com/article-xyz will return a 404
});
});
Route::domain('other.com')->group(function () {
Route::get('article-abc', function (string $id) {
// this route will only work on other.com
// example.com/article-abc will return a 404
});
});
Of course, you also need to do some setup outside your Laravel app to point multiple domains to the same application, but once that's done, you can do per-domain routing inside your web.php
routes file.
Here to help,
Joel
P.S. Do you ever wish you had a trusted group of Laravel developers you could ask for advice? Hit reply if you'd like to be notified when our private Slack community is open to new members.