The Darren Mulholland

Renowned internet personality.

Apache Cheatsheet

A no-frills checklist for installing and configuring Apache on Ubuntu 16.04.

Install Apache

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.

Create Site Directories

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

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

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

Create Virtual Host Files

Create a virtual host file for each site:

sudo vim /etc/apache2/sites-available/

Add the following content:

<VirtualHost *:80>
    DocumentRoot /var/www/
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

Enable Virtual Host Files

Use the a2ensite tool to enable each site:

sudo a2ensite
sudo service apache2 reload

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

Configure Logrotate

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; 

Enable HTTPS

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-letsencrypt-apache

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

sudo letsencrypt --apache

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

sudo letsencrypt 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/letsencrypt renew >> /var/log/le-renew.log

This will run the renew command at 00:30 each day and pipe the output to a log file. 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.