Apache: Install

Apache should be installed by default on Ubuntu but we can check if an updated version is available:

sudo apt update
sudo apt upgrade apache2

The server can be managed using the following commands:

sudo service apache2 start
sudo service apache2 stop
sudo service apache2 restart

Apache is automatically configured on Ubuntu to restart itself each time the server reboots.

Apache: Create Site Directories Cheat Sheet

Create a directory for each site under the /var/www directory:

sudo mkdir -p /var/www/example.com
sudo chown -R $USER:$USER /var/www/example.com

The second command sets the current user as owner of the new site directory.

Apache: Create Virtual Host Files Cheat Sheet

Create a virtual host file for each site:

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

Add the following content:

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

Apache: Enable Virtual Host Files Cheat Sheet

Use the a2ensite tool to enable each site:

sudo a2ensite example.com.conf
sudo service apache2 reload

The reload the command instructs the application to reload its configuration files.

Apache: Configure Logrotate Cheat Sheet

Installing Apache on Ubuntu automatically configures the logrotate utility to rotate the webserver’s logs on a weekly basis. This behaviour can be customized in the /etc/logrotate.d/apache2 file.

The following configuration will rotate the log files on a monthly basis:

/var/log/apache2/*.log {
    rotate 12
    create 640 root adm
    dateformat -%Y-%m
        if /etc/init.d/apache2 status > /dev/null ; then \
            /etc/init.d/apache2 reload > /dev/null; \
        if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
            run-parts /etc/logrotate.d/httpd-prerotate; \

Apache: Enable HTTPS Cheat Sheet

The good folks at the Let’s Encrypt project have made supporting encrypted connections ridiculously easy.

First install Certbot, the Let’s Encrypt client:

sudo apt install python-certbot-apache

Let Certbot obtain and install a domain validation certificate for your site(s):

sudo certbot --apache

Let’s Encrypt certificates last for 90 days but can be renewed automatically using the renew command:

sudo certbot renew

We can set up a cron job to run this command automatically. Edit the root user’s crontab using:

sudo crontab -e

Add the following line:

30 0 * * * /usr/bin/certbot renew

This will run the renew command at 00:30 each day. Note that renew only renews certificates that are actually expiring so running the command daily does not place an unnecessary burden on the Let’s Encrypt servers.