How to Redirect HTTP to HTTPS in Apache Config

Image : How to Redirect HTTP to HTTPS in Apache Config

If you want to force HTTPS redirection in Apache, the best practice is to set it up directly in the Apache main configuration or virtual host files. This approach is faster and more efficient than .htaccess because Apache parses these files once at startup rather than on every request.

<—- INSERT VIDEO HERE  —->

Why Redirect HTTP to HTTPS in Apache?

    • Ensures secure communication with SSL/TLS encryption.
    • Improves SEO rankings since Google favors HTTPS sites.
    • Protects user data from interception.
    • Complies with security best practices and browser warnings.

How to Force HTTPS Redirect in Apache Configuration

Step 1: Locate Your Apache Configuration Files

    • Your virtual host configuration file for Ubuntu is located at  /etc/apache2/sites-available/.

Step 2: Create an SSL/port 443 Apache Virtual Host Configuration.

I show how to create a self signed SSL certificate for Apache in Ubuntu 24.04 in this article : https://www.phpcoderusa.com/how-to-create-a-self-signed-ssl-certificate-for-apache-in-ubuntu-24-04/ 

Step 3: Edit Your Virtual Host Configuration for Port 80 (HTTP)

Add a redirect directive to send all traffic to HTTPS by adding the following 2 line:

# Redirect all HTTP requests to HTTPS
Redirect permanent / https://www.example.com/

Replace https://www.example.com with your domain.

Step 4: Restart Apache

    • sudo systemctl restart apache2

Always backup config files before making changes.

Step 5. Verify SSL Certificate:

Use openssl to test:

echo -e "GET / HTTP/1.1\r\nHost: <-domain.tld->\r\nConnection: close\r\n\r\n" | openssl s_client -connect <-domain.tld->:443 -servername <-domain.tld-> -quiet

Look for:

    • Verify return code: 0 (ok)
    • error:num=18:self-signed certificate : this is normal.
    • Run : sudo apache2ctl configtest – which will return “Syntax OK”

Step 6. Check with a Browser:

    • Visit https://<-domain.tld-> to verify. (ensure it is https)
    • Since this is self signed, there will be an SSL warning.

Summary

To force HTTPS redirect in Apache without using .htaccess files, configure the redirect inside your Apache virtual host configuration for port 80. This method is cleaner, faster, and better for performance and security.