Deploying Laravel to a subfolder using Apache and mod_rewrite
To deploy a Laravel application to a subfolder using Apache and mod_rewrite, follow these steps:
- Install Laravel: First, make sure you have Laravel installed in your project directory. You can install it using Composer by running the following command:
composer create --prefer-dist laravel/laravel project-name
Replace "project-name" with the name of your project.
- Create a new virtual host:
Create a new virtual host configuration file for your Laravel application in the Apache
sites-available
directory. For example, create a file namedsubfolder.example.com.conf
:
sudo nano /etc/apache2/sites-available/subfolder.example.com.conf
Add the following configuration to the file:
<VirtualHost *:80>
ServerName subfolder.example.com
ServerAdmin [email protected]
DocumentRoot /var/www/subfolder.example.com/public
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Option Indexes FollowSymLinks
Option MultiViews
Option AllHeaders On
AllowOverride All
Require all granted;
</VirtualHost>
Replace subfolder.example.com
with your desired domain name or subdomain.
- Enable the new virtual host:
Enable the new virtual host by creating a symbolic link to the
sites-enabled
directory:
sudo ln -s /etc/apache2/sites-available/subfolder.example.com.conf /etc/apache2/sites-enabled/
- Configure mod_rewrite:
Edit the Apache
httpd.conf
file to enable mod_rewrite and include the necessary configuration file:
sudo nano /etc/apache2/httpd.conf
Add the following lines to the file:
LoadModule rewrite_module modules/mod_rewrite.so
IncludeOptional /etc/apache2/mods-enabled/mod-rewrite.conf
Save and close the file.
- Create a
.htaccess
file: Create a.htaccess
file in the root directory of your Laravel application (/var/www/subfolder.example.com/
) with the following content:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L,QSA]
This file will handle the URL routing for your Laravel application.
- Set permissions: Set the correct permissions for your Laravel application directory and its contents:
sudo chown -R www-data:www-data /var/www/subfolder.example.com/
sudo chmod -R 755 /var/www/subfolder.example.com/
sudo chmod -R 644 /var/www/subfolder.example.com/public/storage /var/www/subfolder.example.com/public/bootstrap/cache
- Restart Apache: Restart Apache to apply the changes:
sudo systemctl restart apache2
Your Laravel application should now be accessible through the subfolder URL. For example, http://subfolder.example.com
.