How to Create an Apache Virtual Host on Ubuntu and Obtain a Free SSL Certificate From Let’s Encrypt

Here are the steps to create an Apache virtual host on Ubuntu and obtain an SSL certificate from Let’s Encrypt. For this example, let’s assume your domain is example.com and the application files will be stored in your home directory /home/yourusername/example.com.

Step 1: Install Apache

First, make sure Apache is installed on your Ubuntu system:

sudo apt update
sudo apt install apache2

Step 2: Create a Directory for Your Application

Store your application files in a directory in your home:

mkdir -p /home/yourusername/example.com

Step 3: Create a Symlink to /var/www

Create a symbolic link pointing to your application directory:

sudo ln -s /home/yourusername/example.com /var/www/example.com

Step 4: Create an Apache Virtual Host Configuration

Create a new configuration file for your virtual host:

sudo nano /etc/apache2/sites-available/example.com.conf

Add the following configuration to the file (make sure to replace youradmin@example.com with your actual email and example.com with your actual domain name):

<VirtualHost *:80>
    ServerAdmin youradmin@example.com
    ServerName example.com
    ServerAlias www.example.com

    DocumentRoot /var/www/example.com

    <Directory /var/www/example.com>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Step 5: Enable the Virtual Host

Enable the new virtual host configuration:

sudo a2ensite example.com.conf

Disable the default virtual host if it’s still enabled:

sudo a2dissite 000-default.conf

Step 6: Reload Apache

Reload Apache to apply the changes:

sudo systemctl reload apache2

Step 7: Install Certbot

Install Certbot and the Apache plugin for Let’s Encrypt:

sudo apt install certbot python3-certbot-apache

Step 8: Obtain an SSL Certificate

Run Certbot to obtain and install the SSL certificate:

sudo certbot --apache

Follow the prompts to complete the process. Certbot will automatically configure your virtual host to use SSL.

Step 9: Verify SSL Configuration

After Certbot is done, your virtual host configuration file will have been modified to include SSL directives. You can verify it by checking the configuration file:

sudo nano /etc/apache2/sites-available/example.com-le-ssl.conf

Step 10: Test SSL

Visit https://example.com to make sure everything is working properly. You can use an SSL checker like SSL Labs’ Test to verify the installation.

Step 11: Set Up Auto-Renewal

Certbot sets up a cron job to auto-renew your certificates. To ensure auto-renewal works correctly, you can test it:

sudo certbot renew --dry-run

That’s it! You’ve successfully set up an Apache virtual host and installed a Let’s Encrypt SSL certificate on Ubuntu.