Config Virtual Host for project Laravel

Tram Ho

Certainly, you have encountered the case of dividing multiple domains for one website. A simple example is the sales site ” webbanhang.com ” and the admin page for that sales web page ” admin.webbanhang.com “.

In this article, we will discuss how to configure Virtual Host for a Laravel project locally using Apache as a web server.

What is virtual host?

Virtual host is a definition that only functions to embed multiple domains into one IP address of a server. And by private installation, the Server will know which domain names will work in any folder. This means a lot because we do not need each domain name an IP address, just a server can embed hundreds of domains working together.

Config Apache to use Virtual host

We need apache to configure a virtual host. If you have not installed apache, you can follow the instructions at this link: https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-ubuntu- 18-04 .
One of the most common problems when configuring a Laravel project on an Apache HTTP Server is that mod_writer is not enabled. Laravel needs a mod_writer to convert the URL to its routing through .htaccess
On some Ubuntu platforms, the default mod_writer will be enabled, but for security reasons the default is now disabled. To enbale mod_writer we need to run the command

Create virtual host

To create a new virtual host we need to create a new config file, which will declare the name of our virtual host. Here I will for example have 2 websites: 1 is localdriver.local and 2 is admin.localdriver.local.
You need admin privileges to manipulate those files, so don’t forget to use sudo if you don’t have root access.

Edit config file

The config file will look like this after it is created.

Please correct the following:

Add the entry to the host

Above you have admin.localdriver.local as the server name. We need to configure the system so that when we enter admin.localdriver.local in the browser, it redirects to localhost.
To do this we need to add the entry to the host file of the machine

Add this line at the end of the file

Now that the config is done, we need to activate the new site.

Then reload apache server again

With the localdriver.local page, you can do the same

Install the Laravel project

Prepare the env file

In the project env file change APP_URL and add APP_ADMIN_URL as follows:

Route declaration

We have 2 different domains, so now we need to split the route by domain. Here I will simply group the routes by domain

Test

We are done preparing. Now let’s run it

Share the news now

Source : Viblo