Skip to content

Instantly share code, notes, and snippets.

@obrassard
Last active May 30, 2019 01:00
Show Gist options
  • Save obrassard/1f75eec5d9e8bb2b7d070fdc33a4c9cf to your computer and use it in GitHub Desktop.
Save obrassard/1f75eec5d9e8bb2b7d070fdc33a4c9cf to your computer and use it in GitHub Desktop.

Setup Virtual Host and configure HTTPS with Certbot on Ubuntu

A little walkthrough to setup a new apache virtual host with an HTTPS certificate on Ubuntu.

How to setup a new Virtual Host

Install apache2

sudo apt-get update
sudo apt-get install apache2

Create directory structure

sudo mkdir -p /var/www/example.com/public_html

Grant permissions for not root user (optional)

sudo chown -R $USER:$USER /var/www/example.com/public_html
sudo chmod -R 755 /var/www

Create demo page

echo "<h1>Hello world</h1>" >  /var/www/example.com/public_html/index.html

Create New Virtual Host Files

You may copy the default file 000-default.conf to get started

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.com.conf

Here's an example of the requiredconfig file :

<VirtualHost *:80>
    ServerAdmin admin@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Enable the New Virtual Host

sudo a2ensite example.com.conf
sudo apache2ctl configtest
sudo systemctl restart apache2

How to setup HTTPS with certbot

Installing Certbot

sudo add-apt-repository ppa:certbot/certbot
sudo apt install python-certbot-apache

Allow HTTPS connections if using UFW

sudo ufw allow 'Apache Full'
sudo ufw status

Create certificate

sudo certbot --apache -d example.com -d www.example.com

Test Certbot Auto-Renewal

sudo certbot renew --dry-run

✨ Done


💡 If your prefer, I have also made a shell script to create new vhost easily, see vhost-setup.sh. Apache2 and certbot must be installed on your machine before running the script.

bash vhost-setup.sh example.com
#! /bin/bash
if [ -z $1 ];
then echo "Error: Please provide a domain name"; exit;
fi
echo "📦 Creating directories"
sudo mkdir -p /var/www/$1/public_html
echo "<h1>Hello world from $1</h1>" > /var/www/$1/public_html/index.html
echo "🛠 Creating $1 virtual host"
echo "<VirtualHost *:80>
ServerAdmin admin@$1
ServerName $1
DocumentRoot /var/www/$1/public_html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>" > /etc/apache2/sites-available/$1.conf
echo "🚀 Enabling virtual host"
sudo a2ensite $1.conf
sudo systemctl restart apache2
echo "🤖 Creating certificate with certbot"
sudo certbot --apache -d $1
sudo certbot renew --dry-run
echo "✨ Done !"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment