Configuring VirtualHost in Apache with SSL and IP redirection

This is a guide on how to configure VirtualHost in Apache with support for SSL and IP redirection.

You will need:

I used the Electronic Frontier Foundation's Certbot CLI tool to generate and automatically renew my Let's Encrypt certificates.

With Apache installed, edit /etc/httpd/conf/httpd.conf and add the following line at the bottom:

IncludeOptional sites-available/*.conf

Then create two *.conf files for your domain at the following path. The file postfixed with le-ssl will be your SSL configuration for port 443:

/etc/httpd/sites-available/<domain>.conf
/etc/httpd/sites-available/<domain>-le-ssl.conf

Paste the following in /etc/httpd/sites-available/<domain>.conf:

# Redirect `http://<ip-address>` to `https://<domain>`
<VirtualHost _default_:80>
    ServerName <ip-address>
    Redirect / https://<domain>
</VirtualHost>

# Set up `http://<domain>` and include rewrite logic to redirect to HTTPS.
<VirtualHost *:80>
    ServerName <domain>
    ServerAlias <domain>
    DocumentRoot /var/www/<domain>/html
    ErrorLog /var/www/<domain>/log/error.log
    CustomLog /var/www/<domain>/log/requests.log combined
    RewriteEngine on
    RewriteCond %{SERVER_NAME} =<domain>
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

If you have a Lets Encrypt certificate for SSL you should also have this config for the HTTPS site:

Then paste the following in /etc/httpd/sites-available/<domain>-le-ssl.conf:

<IfModule mod_ssl.c>
    # Redirect `https://<ip-address>` to `https://<domain>`
    <VirtualHost _default_:443>
        ServerName <ip-address>
        Redirect / https://<domain>
    </VirtualHost>

    # Set up `https://<domain>`.
    <VirtualHost *:443>
        ServerName <domain>
        ServerAlias <domain>
        DocumentRoot /var/www/<domain>/html
        ErrorLog /var/www/<domain>/log/error.log
        CustomLog /var/www/<domain>/log/requests.log combined
        SSLCertificateFile /etc/letsencrypt/live/<domain>/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/<domain>/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf
    </VirtualHost>
</IfModule>

Run systemctl restart httpd for the configuration to take effect.

Place your website files in /var/www/<domain>/html/ and then visit your URL. Double check server logs are being sent to /var/www/<domain>/logs/ as well.

Redirection should work as follows:

http://<domain> to https://<domain>
http://<ip-address> to https://<domain>
https://<ip-address> to https://<domain>

Note that going to https://<ip-address> will result in a security warning but if you click "accept" you will be redirected to https://<domain>. This is unavoidable (you cannot assign certificates to IP addresses) but having the redirection logic in place is nice to have.