How to Configure Virtual Host for Laravel
How to Configure Virtual Host for Laravel
Learn how to set up virtual hosts for your Laravel applications on Apache and Nginx web servers.
Introduction
Virtual hosts allow you to run multiple websites on a single server. This guide will show you how to configure virtual hosts for your Laravel applications using both Apache and Nginx web servers.
Prerequisites
- Apache or Nginx web server installed
- Laravel application
- Root or sudo access
- Basic understanding of web server configuration
1 Apache Virtual Host Configuration
Create a new virtual host configuration file:
sudo nano /etc/apache2/sites-available/laravel.conf
Add the following configuration:
<VirtualHost *:80>
ServerName laravel.local
DocumentRoot /var/www/laravel/public
<Directory /var/www/laravel/public>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/laravel_error.log
CustomLog ${APACHE_LOG_DIR}/laravel_access.log combined
</VirtualHost>
Enable the site and restart Apache:
sudo a2ensite laravel.conf
sudo systemctl restart apache2
2 Nginx Virtual Host Configuration
Create a new Nginx configuration file:
sudo nano /etc/nginx/sites-available/laravel
Add the following configuration:
server {
listen 80;
server_name laravel.local;
root /var/www/laravel/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
Enable the site and restart Nginx:
sudo ln -s /etc/nginx/sites-available/laravel /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
3 Configure Local Hosts File
Add the domain to your local hosts file:
sudo nano /etc/hosts
Add this line:
127.0.0.1 laravel.local
4 Set Proper Permissions
Set the correct permissions for your Laravel application:
sudo chown -R www-data:www-data /var/www/laravel
sudo chmod -R 755 /var/www/laravel
sudo chmod -R 775 /var/www/laravel/storage
sudo chmod -R 775 /var/www/laravel/bootstrap/cache
Key Features Covered
- Apache virtual host configuration
- Nginx virtual host configuration
- Local hosts file setup
- File permissions management
- SSL configuration (optional)
Best Practices
- Use descriptive domain names
- Keep configuration files organized
- Regularly check error logs
- Use SSL for production environments
- Maintain proper file permissions
Common Issues
- Permission denied errors
- Configuration syntax errors
- Missing PHP modules
- Incorrect document root
- Cache issues