Creating Virtual Hosts and configuring Apache2 to serve from there.
Tags: virtualhosts, apache2, laravel, linux
Published: 2023-05-19 21:08:41

This is a detailed explanation of how to configure apache2 server on Linux to serve website (Laravel) from virtual host. It aroused due to a problem i faced when converting a laravel 8 app to serve from local host instead of the public folder of laravel.

After multiple attempts, i managed to hack a clean way to do this without changing the Apache config files: *Virtual Hosts is the answer.*

## Requirements
- Apache2 web server
- PHP installed
- A laravel App.

## Steps

### Add domain name for your site to `/etc/hosts` file. 
I tend to call my local sites `.test`  for example `demo.test` and Point your site to localhost (127.0.0.1)
    
    ```bash
    $ sudo nano /etc/hosts
    
    # add the following line to the file
    127.0.0.1          demo.test
    ```
    

### Create a virtual host for your site. 
Assuming your site is hosted in the `/var/www/html/demo` folder which is true in my case; 
 - Change directory to sites-available folder
        
         `$ cd /etc/apache2/sites-available`
 - Copy the default configuration sites file to a new file, in my case which would be ‘*demo.conf’*
        
        `$ sudo cp 000-default.com.conf demo.conf`. 
 - Add the following lines to newly created configuration file. `sudo nano demo.conf`
        
        ```bash
        <VirtualHost *:80>
            ServerAdmin admin@demo.test
            ServerName demo.test
            ServerAlias www.demo.test
            DocumentRoot /var/www/html/demo
            <Directory /var/www/html/demo>
                Options Indexes FollowSymLinks
                AllowOverride All
                Require all granted
            </Directory>
            ErrorLog ${APACHE_LOG_DIR}/error.log
            CustomLog ${APACHE_LOG_DIR}/access.log combined
            <IfModule mod_dir.c>
                DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
            </IfModule>
        </VirtualHost>
        ```

> Note that my site is located at `/var/www/html/demo`, and I use that as my `DocumentRoot` in the above configuration. Replace it accordingly. Also, the server name `demo.test` is the one I added to my `/etc/hosts` file

> Just to clarify, in step 2 you will need to create a new file named `demo.conf` and add the configuration lines to it. The command you provided `$ sudo cp 000-default.com.conf demo.conf` will not work, it should be `$ sudo cp 000-default.conf demo.conf` instead

### Enable the Configuration file.
    
    `a2ensite` enables the specified site within the `apache2` configuration. It creates a symlink within `/etc/apache2/sites-enabled` (not sites-available).
    
    `$ sudo a2ensite demo.conf`

### Restart apache2 service
    
    `$ sudo systemctl restart apache2`
    
### Open your project in  Vs code and change the root `.htaccess` file to:
    
    ```xml
    <IfModule mod_rewrite.c>
        <IfModule mod_negotiation.c>
            Options -MultiViews -Indexes
        </IfModule>
    
        RewriteEngine On
    
        # Handle Authorization Header
        RewriteCond %{HTTP:Authorization} .
        RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    
        # Redirect Trailing Slashes If Not A Folder...
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_URI} (.+)/$
        RewriteRule ^ %1 [L,R=301]
    
        # Send Requests To Front Controller...
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [L]
    
    </IfModule>
    ```
    
### Clear laravel cache using `php artisan config:clear` and open your browser and type `demo.test`.

> As the final step in this process, it's important to test your website and ensure everything is functioning as expected.

Open your browser and type in the domain name you specified in the previous steps, in this case "demo.test". If everything has been configured correctly, your website should now be live and accessible through this domain.

If you encounter any issues or errors, double check each step of the process to ensure everything has been properly executed. Additionally, consult online resources or seek help from a professional if needed.

*Good luck with your virtual hosting and Apache configuration!*