Sub-domain routing in Laravel with Nginx In Ubuntu

Mahmud
1 min readJun 26, 2018

--

Step #1 — (Nginx configuration):

Create a virtual host block in Nginx. Go to /etc/nginx/sites-available/ . Run the following command

cd /etc/nginx/sites-available/

Here you will find a default nginx configuration file named “default”. Copy “default” file and name it “example.local”. Here “example.local” is our domain. Change the domain according to your need.

// Copy default as example.local
sudo cp ./default ./example.local
// Open example.local file in editor
sudo vim example.local

After that configure the “example.com” file as following.

In line #4, write project path correctly

In line #15, Change if you are using a php version other than 7.2

Then run the following command

sudo ln -s /etc/nginx/sites-available/example.local /etc/nginx/sites-enabled/

Open And edit the file /etc/nginx/nginx.conf

sudo vim /etc/nginx/nginx.conf 

Uncomment the line server_names_hash_bucket_size 64; Remove # sign

Then restart Nginx

sudo service nginx restart

Open /etc/hosts file

sudo vim /etc/hosts

Add the following sub-domains. Change as you need.

127.0.0.1       example.local 
127.0.0.1 admin.example.local
127.0.0.1 partner.example.local

Step #2 — (Laravel Routing)

Add these following routes in routes/web.php

Route::domain('admin.example.local')->group(function () {
Route::get('/', function () {
return 'Response from admin.example.local';
});
});

Route::domain('partner.example.local')->group(function () {
Route::get('/', function () {
return 'Response from partner.example.local';
});
});

Route::get('/', function () {
return 'Response from example.local';
});

And Visit the following URLs to see the output.

http://example.local

http://admin.example.local

http://partner.example.local

And here we go!

--

--