Search code examples
linuxhostwildcard-subdomaindnsmasq

Automatically create a sub-domain for laravel application using wild card dns


I am using laravel5.5 and I'm implementing the wild card dns giving each user their own sub-domain.

In my implementation, I am working on a laptop with windows 10 and a laragon server.

On laragon I setup like this

<VirtualHost *:80>
    DocumentRoot "C:/laragon/www/tindahan/public/"
    ServerName tindahan.local
    ServerAlias *.tindahan.local
    <Directory "C:/laragon/www/tindahan/public/">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

and on the host file

127.0.0.1      tindahan.local       
127.0.0.1      fil.tindahan.local   
127.0.0.1      liz.tindahan.local     

On the route

Route::get('/', function () {
  $url       = parse_url(url()->current());
  $domain    = explode('.', $url['host']);
  $subdomain = $domain[0];

  dd($subdomain);
});

So when visiting the fil.tindahan.local or liz.tindahan.local, I got the result

fil and Liz

but if I visit joseph.tindahan.local I got this error

This site can’t be reached

I need to create another sub-domain on the host to make it work.

The question is, how can do it automatically?

when I enter any names as a sub-domain it should be automatically created so that I never do it manually?


Solution

  • As far as I know, the error will resolved in network layer, not from application layer (in this case laravel).

    I think you need your own local DNS-Server.

    I've used dnsmasq in Linux (ubuntu) and it worked fine.

    steps:

    1. apt install dnsmasq
    2. open /etc/dnsmasq.conf with an editor.
    3. add address=/your_domain.loc/127.0.0.1 (it's just an example so you'll need change domain and ip probably).
    4. run sudo systemctl restart dnsmasq to restart the service.
    5. Well, you can test any url from your_domain.loc in your browser and you will not get that error ;)

    goodluck