Many websites give their users a custom subdomain for their profiles or pages, so the user can access his profile at http://username.website.com, which is much better. In this post, we will see how to make dynamic Laravel subdomain routing efficiently.

Configure DNS

To do this trick, you need to have access to the DNS server settings and apache web server settings.

First, you need to add an A record with an asterisk for the subdomain like this:

* IN A 192.168.1.5

You should replace the IP address with your IP address.

Configure web server

Open Apache web server configuration file httpd.conf and add a VirtualHost like this:

<VirtualHost *:80> ServerName website.com ServerAlias *.website.com </VirtualHost>

Let’s assume that we have the users with the name field which will contain the user’s name.

Now we will create our route.

Route::get('/', function () { $url = parse_url(URL::all()); $domain = explode('.', $url['host']); $subdomain = $domain[0]; $name = DB::table('users')->where('name', $subdomain)->get(); dd($name); // write the rest of your code. });

First, we explode the URL and extract the host from it; then, we get the subdomain part.

Then we search for a username in the users’ table that matches the extracted subdomain.

You can check if no user found, redirect to another page, or give him an error message or whatever.

Now, if you try to visit any user subdomain like http://likegeeks.website.com, you should see the user’s name without problems.

Keep in mind that the user that you are visiting his subdomain MUST be present in the database.

Any user added to the database will have his subdomain automatically without a headache.

If you don’t have access to your web server configuration like using shared hosting or so, you can’t achieve the same functionality using htaccess redirection.

Multiple routes in subdomain

In the above example, we use a single route to deal with the subdomain, but you can use many routes with a subdomain.

You can use routes groups to achieve this:

Route::group(array('domain' => '{subdomain}.website.com'), function () { Route::get('/', function ($subdomain) { $name = DB::table('users')->where('name', $subdomain)->get(); dd($name); }); });

As you see, Laravel subdomain routing is very easy to implement. I hope you find the post useful. Keep coming back.

Thank you.