Creating a virtual host is the way to go if you're working on a Laravel project and want to access it through a custom domain instead of using localhost. A virtual host allows you to configure Apache to serve your Laravel application from a specific domain name.
This guide will walk you through setting up a virtual host for your Laravel application on Ubuntu simply and easily.
How to Create a Virtual Host for Laravel Application in Ubuntu 20.04/22.04
Before starting, ensure your system is up to date and Apache is installed. Run the following commands:
sudo apt update
sudo apt install apache2
Enable the Apache rewrite module, as it's essential for Laravel:
sudo a2enmod rewrite
sudo systemctl restart apache2
Navigate to your web directory (e.g., /var/www/html
) and clone or copy your Laravel project:
cd /var/www/html
sudo git clone https://github.com/your-repository/laravel-app.git
Change the ownership of the project directory to the Apache user (www-data
):
sudo chown -R www-data:www-data /var/www/html/laravel-app
Set the correct permissions:
sudo chmod -R 775 /var/www/html/laravel-app/storage /var/www/html/laravel-app/bootstrap/cache
Create a new Apache configuration file for your Laravel project:
sudo nano /etc/apache2/sites-available/laravel-app.conf
Add the following configuration to the file, replacing laravel-app.test
with your custom domain and /var/www/html/laravel-app/public
with your Laravel project’s public directory:
<VirtualHost *:80>
ServerName laravel-app.test
DocumentRoot /var/www/html/laravel-app/public
<Directory /var/www/html/laravel-app/public>
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/laravel-app_error.log
CustomLog ${APACHE_LOG_DIR}/laravel-app_access.log combined
</VirtualHost>
Save and exit the file by pressing Ctrl + O
, then Enter
, followed by Ctrl + X
.
Enable the new configuration file:
sudo a2ensite laravel-app.conf
Reload Apache to apply the changes:
sudo systemctl reload apache2
To access your Laravel application via the custom domain, add it to your system's hosts
file:
sudo nano /etc/hosts
Add the following line at the end of the file:
127.0.0.1 laravel-app.test
Save and exit the file.
Open your browser and visit http://laravel-app.test
If everything is set up correctly, you should see your Laravel application's homepage.
mod_rewrite
module is enabled using sudo a2enmod rewrite
.sudo a2enmod actions fcgid alias proxy_fcgi
You might also like: