Steps to Configure Apache for Laravel
Ensure Apache is Installed and Running
Make sure Apache is installed and running:
sudo apt update
sudo apt install apache2
sudo systemctl start apache2
sudo systemctl enable apache2
Enable Apache Rewrite Module
Enable the mod_rewrite module, which is necessary for URL rewriting:
sudo a2enmod rewrite
sudo systemctl restart apache2
Configure Apache Virtual Host
Modify your Apache virtual host configuration to point to Laravel’s public directory.
Edit the default Apache configuration file or create a new virtual host file:
sudo nano /etc/apache2/sites-available/000-default.conf
Update the <VirtualHost> block to look something like this:
apache
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/your-laravel-project/public
<Directory /var/www/html/your-laravel-project/public>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Set Permissions for Laravel Directories
Ensure that the necessary directories have the correct permissions:
sudo chown -R www-data:www-data /var/www/html/your-laravel-project/storage /var/www/html/your-laravel-project/bootstrap/cache
sudo chmod -R 775 /var/www/html/your-laravel-project/storage /var/www/html/your-laravel-project/bootstrap/cache
Restart Apache
Restart Apache to apply the changes:
sudo systemctl restart apache2
Alternative: Using .htaccess to Redirect Requests
If you want to keep your current Apache configuration and use .htaccess to handle redirections, you can add a rewrite rule in the root directory's .htaccess file.
Create or Update the .htaccess File in the Root Directory
Create or update the .htaccess file in the root of your Laravel project (not the public directory):
sudo nano /var/www/html/your-laravel-project/.htaccess
Add the following content to redirect all requests to the public directory:
apache
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
Ensure Apache Allows .htaccess Overrides
Ensure your Apache configuration allows .htaccess overrides by setting AllowOverride All for the project directory. Edit the virtual host file:
sudo nano /etc/apache2/sites-available/000-default.conf
Ensure it looks like this:
apache
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/your-laravel-project
<Directory /var/www/html/your-laravel-project>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Restart Apache
Restart Apache to apply the changes:
sudo systemctl restart apache2