How to Configure Subdomain routes in Laravel for Domain Driven Design

https://twtv3.ams3.digitaloceanspaces.com/subdomain-routes-laravel.jpg

Also Read: Structure Laravel App for DDD 

Also Read: Routes in Laravel for DDD

If you need to access your routes based on subdomains like product.thewebtier.com/products. To achieve this, you need to modify your route definitions in Laravel and configure web server to handle subdomains.

Modify your route definitions

First, update your route definitions to use subdomain-based routing in the app/Domain/Product/routes/web.php or app/Domain/Product/routes/api.php file.

Also Read: Create own PHP Router

For example, in app/Domain/Product/routes/web.php:

<?php
use App\Domain\Product\Controllers\ProductController;
use Illuminate\Support\Facades\Route;
Route::domain('product.thewebtier.com')->group(function () {
    Route::get('/products', [ProductController::class, 'index'])->name('products.index');
    // Add other product routes here
});

Similarly, you can define routes for other domains in their respective route files.

Configure your Web Server

You need to configure your web server (e.g., Apache or Nginx) to handle subdomains and point them to your Laravel application.

Nginx configuration for DDD

Following example code will work for Nginx configuration for setting up subdomain routing for Laravel application in DDD.

server {
    listen 80;
    server_name product.thewebtier.com;
    root /path/to/laravel/public;
    index index.php index.html index.htm;
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    }
    location ~ /\.ht {
        deny all;
    }
}

Apache configuration for DDD

For Apache, create or modify the virtual host configuration:

<VirtualHost *:80>
    ServerName product.thewebtier.com
    DocumentRoot /path/to/laravel/public
    <Directory /path/to/laravel/public>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Make sure to replace /path/to/laravel with the actual path to your Laravel application.

Configure your DNS

Add a DNS record (A or CNAME) for the subdomain (product.thewebtier.com) and point it to your server’s IP address or domain.

Also Read: MySQL backups in Laravel

After completing these steps, you should be able to access your routes using the subdomain-based URL, like product.thewebtier.com/products.

Laravel News Links