Wildcard Site for Laravel Homestead

Laravel is a fantastic PHP framework. Homestead makes it even easier to do Laravel development. It’s basically a prebuilt Vagrant VM so you can build Laravel projects without having to worry about setting up the server environment first.

If you’re not familiar with Vagrant, it’s another extremely useful tool to create easily reproducible development environments. You create a Vagrantfile, which serves as a recipe for a virtual machine. You can give that single text file to another developer or copy it to your laptop if you’re traveling, then run vagrant up and you will get an identical environment.

Now back to Homestead.

A minor nuisance with Homestead is that you need to configure a new site configuration for each project you’re developing. You can do this in one of two ways. First, you can add them to the Homestead.yaml. Second, you can run the serve script in a running Homestead VM. In either case, you also have to add an entry for the new site in your hosts file.

Before I started using Homestead, I used a vagrant box that I had configured to use regular expressions in nginx. This allowed me to have a single nginx configuration for all my projects. It was really convenient, but I thought it wouldn’t work with Homestead. I was wrong.

Let’s say you use the format of project_name.app for your Laravel projects. For example, if your project was named waldo, you would browse to waldo.app (after having updated your hosts file) to see the site. Normally, you’d need to have something like this in your Homestead.yaml:

folders:
    - map: (path to your Laravel projects)
      to: /home/vagrant/Code

sites:
    - map: waldo.app
      to: /home/vagrant/Code/waldo/public

    - map: franklin.app
      to: /home/vagrant/Code/franklin/public

    - map: henry.app
      to: /home/vagrant/Code/henry/public

    - map: phil.app
      to: /home/vagrant/Code/phil/public

And so on, for each project. Instead, you can use this:

folders:
    - map: (path to your Laravel projects)
      to: /home/vagrant/Code

sites:
    - map: '~^(?<project>.+)\.app$'
      to: /home/vagrant/Code/\$project/public

And it will work for any number of sites as long as you use the same project_name.app format.

The file that’s created in /etc/nginx/sites-available won’t look pretty, but it removes a step from your development process. And if you’re anything like me, efficiency is bliss.

Comments are closed