How to setup Specific Subdomain routing in Laravel
Adi · 28/May/20
Hi all, this is Adi, again with another Laravel post. In one of my recent projects, I had to set up specific subdomain routing within the same Laravel application. This was something new to me because on most projects, I just work with one domain and everything is accessed
/ after it. I am going to share with you how I solved it, I hope it gives you some ideas when you are faced to do this too. Let’s get started.
What was my need
First, let’s explore my requirements for this project. My client wanted to access the admin portal from the
admin.myapp.com domain, the marketing website from
myapp.com, and the API from
api.myapp.com. As you can see it defers from Laravel’s defaults. By default, Laravel exposes API routes in
myapp.com/api url and everything else in
Laravel routing provides a convenient way to setup subdomain routing but it works best only when you have a wildcard routing, this
*.myapp.com works but to make specific subdomain to work, I had to do some config changes as well. Below is my
As you can see, you can use the
domain method to mention the subdomain you want to capture, but it becomes complicated when you have multiple environments with different domains you need to use, that’s why I have added the
SITE_URL variable to my
.env file. So when I am developing locally I can set it to
localhost, when in production I set the actual domain, and when in staging or testing I can set the relevant domains.
It’s just another .env variable you set. Pretty simple.
Now you have the routing configured but you need to make a few changes in the webserver setup also to be able to use multiple domain names for the same host. Let’s see how.
I use a windows PC for development, I had to change my
hosts files in the
system32 folder. I added these entries.
Now, if you go to any of these domains, it should be routed to your Laravel application, when it’s being served.
I hope this post helped you. It’s not daily that you come across a config like this, that’s why I decided to share it. If you would like me to cover a specific issue you have with Laravel, do let me know I’ll try to write a post about it.
That’s all for now, this has been Adi.
If you are looking for a Freelance Web Developer you can contact me