Skip to content

How to Redirect HTTP to HTTPS in Apache (Secure Setup)

Redirect HTTP to HTTPS in Apache the right way: a port-80 vhost with one 301 hop, mod_rewrite and .htaccess options, load balancer loops and common mistakes.

Steps
3
Category
Web Servers
Covers
Apache, SSL/TLS
On this page 3 steps

Serving your site over HTTPS only helps if visitors actually end up on HTTPS. This guide shows the best way to redirect HTTP to HTTPS in Apache: a small port-80 virtual host that sends every request to the HTTPS URL in a single 301 hop, with the path and query string intact. It also covers mod_rewrite and .htaccess for when you can’t edit the virtual host, sites behind a load balancer, and the mistakes that cause redirect loops or broken URLs.

Every config here was tested on Ubuntu 24.04 (Apache 2.4.58) and Rocky Linux 10 (Apache 2.4.63). The same configs work on Debian, RHEL, AlmaLinux and other Apache 2.4 systems.

Quick Answer

Add a port-80 virtual host that does nothing but redirect, and keep your real site on port 443:


<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

Keep the trailing slash after the domain in https://example.com/. Then test the config and reload Apache: sudo apache2ctl configtest && sudo systemctl reload apache2 on Ubuntu and Debian, or sudo apachectl configtest && sudo systemctl reload httpd on RHEL-based systems.

Which Method Should You Use?

MethodUse it whenNeeds
A. Redirect in the port-80 vhostYou can edit the server config. Best choice for almost every site.mod_alias (enabled by default)
B. mod_rewrite in the vhostOne vhost serves many hostnames and each must keep its own name.mod_rewrite
C. .htaccessShared hosting, or a CMS that manages .htaccess for you.mod_rewrite + AllowOverride FileInfo

The Apache documentation itself recommends plain Redirect over mod_rewrite for simple redirects like this one. It is faster, too: .htaccess files are re-read on every request, while vhost config is loaded once.

Before You Start

  • HTTPS must already work. Open https://example.com in a browser first. If you don’t have a certificate yet, follow how to set up Let’s Encrypt SSL with Apache on Ubuntu.
  • Enable mod_ssl. On Ubuntu and Debian run sudo a2enmod ssl. On RHEL, Rocky and AlmaLinux install it with sudo dnf install mod_ssl.
  • Know where your vhosts live: /etc/apache2/sites-available/ on Ubuntu and Debian (enable a file with a2ensite), /etc/httpd/conf.d/*.conf on RHEL-based systems.
  • Used Certbot? certbot --apache can add its own HTTPS redirect (a rewrite rule in the port-80 vhost). Check for it before adding another one, so you don’t end up with two redirects.

A complete setup has three virtual hosts: port 80 redirects everything, the HTTPS www host redirects to the main host, and only the main HTTPS host serves content. Replace example.com with your domain, and use www.example.com as the target instead if www is your canonical host:


# 1. Port 80: send every request to the canonical HTTPS URL in one hop
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

# 2. HTTPS www: redirect to the canonical host
<VirtualHost *:443>
    ServerName www.example.com
    SSLEngine on
    SSLCertificateFile    /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    Redirect permanent / https://example.com/
</VirtualHost>

# 3. HTTPS canonical site: the only vhost that serves content
<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/example.com/public
    SSLEngine on
    SSLCertificateFile    /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem

    # Optional, after the redirect works: see the HSTS guide
    # Header always set Strict-Transport-Security "max-age=300; includeSubDomains"
</VirtualHost>

What this gives you, all verified with curl:

  • http://example.com/blog/post?x=1 → https://example.com/blog/post?x=1. Redirect keeps the path and the query string.
  • http://www.example.com/a → https://example.com/a in one hop, not two. Redirect chains slow down the first visit and waste crawl budget.
  • https://www.example.com/ → https://example.com/.
  • Percent-encoded URLs such as /caf%C3%A9 stay valid.

Don’t forget the trailing slash

Redirect appends whatever follows the matched path to the target. With Redirect permanent / https://example.com (no slash), our test sent /blog/post to https://example.comblog/post, which is a broken hostname. Always end the target with /.

301 or 308?

Redirect permanent sends a 301, which is right for normal websites. Browsers may turn a redirected POST into a GET and drop the form data, though. If old clients or API users still post to http:// URLs, use Redirect 308 / https://example.com/. A 308 is just as permanent for search engines, and in our test the POST kept its method through the redirect.

Step 2 of 3Test the Config and Reload Apache

Always check the syntax before you reload. A typo then fails the test instead of taking the site down. Use reload, not restart, so open connections aren’t cut off.

Ubuntu and Debian:

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

RHEL, Rocky Linux, AlmaLinux, Fedora:

sudo apachectl configtest
sudo systemctl reload httpd

The output must say Syntax OK. On Ubuntu, also make sure the stock 000-default.conf doesn’t answer for your domain instead: list enabled sites with ls /etc/apache2/sites-enabled/.

Step 3 of 3Verify the Redirect

Use curl -I to see the status code and the Location header. Add -L to follow the redirect and confirm there is only one hop:

curl -sIL "http://www.example.com/blog/post?x=1" | grep -iE "^(HTTP|location)"
HTTP/1.1 301 Moved Permanently
Location: https://example.com/blog/post?x=1

HTTP/1.1 200 OK

You want exactly one 301 (or 308) followed by a 200. Two or more redirects mean a chain, and an endless list ending in curl: (47) Maximum (50) redirects followed means a loop (see the load balancer section below). Also check a deep URL with a query string, and the bare domain without www.

Option B: mod_rewrite in the Virtual Host

Use this when one port-80 vhost covers several hostnames and each must go to HTTPS on its own name. Enable the module first on Ubuntu and Debian with sudo a2enmod rewrite (RHEL-based systems load it by default):


<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com shop.example.com
    RewriteEngine On
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
</VirtualHost>

Use %{SERVER_NAME}, not %{HTTP_HOST}. HTTP_HOST is the raw Host header, port included. When a client sent Host: example.com:80, the HTTP_HOST rule redirected to https://example.com:80/, which tries TLS on port 80 and fails. SERVER_NAME drops the port.

There is no need for a RewriteCond %{HTTPS} line here, because this vhost only ever receives plain HTTP.

Add a catch-all vhost

Apache sends requests for unknown hostnames, and bare-IP requests, to the first vhost on the port. If that is your rewrite vhost, a request with Host: evil.test gets redirected to https://evil.test/: in our test, Apache redirected an arbitrary hostname. Make a harmless vhost the default by loading it first (for example as 000-catchall.conf):


# Load this first, so it becomes the default vhost for port 80
<VirtualHost *:80>
    ServerName catchall.invalid
    <Location />
        Require all denied
    </Location>
</VirtualHost>

After this, unknown hosts and bare-IP requests get 403 Forbidden, while example.com still redirects. On Ubuntu, disable 000-default.conf if you use this. Option A doesn’t have the problem, because its target is a fixed hostname.

Option C: Redirect HTTP to HTTPS Using .htaccess

If you can’t edit the vhost, for example on shared hosting, put this at the top of the .htaccess file in your document root, before any CMS rules:


RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

The RewriteCond is essential here, because the same .htaccess is read for HTTPS requests too. Without it, you get an endless loop. !=on is an exact string compare and works the same as the commonly seen off.

To redirect www to the bare domain in the same single hop, use this instead:


RewriteEngine On
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]

For the other direction and more variants, see redirecting non-www to www with .htaccess.

If .htaccess seems to do nothing

Two things we hit in testing on a stock install:

  • Nothing happens: Apache ignores .htaccess by default (AllowOverride None on both Ubuntu and Rocky Linux), without any error. Rewrite rules need AllowOverride FileInfo for that directory in the server config, then a reload. See how to enable .htaccess in Apache.
  • 500 Internal Server Error: mod_rewrite isn’t enabled. The error log shows Invalid command 'RewriteEngine'. Run sudo a2enmod rewrite and reload Apache. Don’t “fix” it by wrapping the rules in <IfModule mod_rewrite.c>: the error goes away, but so does the redirect.

<Directory /var/www/example.com/public>
    AllowOverride FileInfo
</Directory>

Behind a Load Balancer, CDN or Proxy: Avoid the Redirect Loop

If TLS ends at a load balancer (AWS ALB, HAProxy, Cloudflare and others) and Apache receives plain HTTP, %{HTTPS} is never on. The HTTPS-only rule then redirects every request, including those that already came in over HTTPS: an endless loop. Our test showed exactly that: a 301 for a request marked X-Forwarded-Proto: https.

Check the header the proxy sets as well:


RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

With this rule, requests forwarded as HTTPS got 200, and plain HTTP still got redirected. Clients can fake X-Forwarded-Proto, so only use this when Apache accepts traffic from the load balancer alone (firewall or security group). Usually the cleanest fix is to let the load balancer do the redirect itself. For AWS, see how to redirect to HTTPS behind an AWS load balancer. On Cloudflare, use the “Full (strict)” SSL mode, not “Flexible”.

After the Redirect: Next Steps

  • Enable HSTS. A redirect still lets the very first request go over plain HTTP. HSTS tells browsers to skip HTTP for your domain entirely. Follow how to enable HSTS in Apache, and start with a short max-age.
  • Fix mixed content. Update hard-coded http:// links to images, scripts and stylesheets. In WordPress, set both site URLs to https://.
  • Update your canonical URLs and sitemap, and add the HTTPS property in Google Search Console.
  • Certificate renewals keep working. Let’s Encrypt HTTP-01 validation follows redirects to HTTPS, so you don’t need an exception for /.well-known/acme-challenge/.

Common Mistakes

  • No trailing slash in Redirect permanent / https://example.com, which turns /page into https://example.compage.
  • Using %{HTTP_HOST} in the rewrite target, which leaks :80 into the HTTPS URL when clients include the port.
  • Redirect chains: http://www → https://www → https://. Send every variant straight to the final URL.
  • A rule without RewriteCond %{HTTPS} in .htaccess or in a shared vhost, causing a loop.
  • Using 302 (the default of Redirect without permanent) for a permanent move. Search engines keep the HTTP URL indexed longer. Use permanent, 301 or 308.
  • Restarting without configtest. One typo in a vhost then stops every site on the server.

Conclusion

The simplest config is also the most robust: a port-80 virtual host with Redirect permanent / https://example.com/, a second redirect for HTTPS www, and content served only from the canonical HTTPS host. Use mod_rewrite or .htaccess only when you have to, check X-Forwarded-Proto behind a proxy, and confirm a single hop with curl -IL. Then add HSTS.

Using Nginx? See how to redirect HTTP to HTTPS in Nginx. For other kinds of redirects, read the guide to 301 redirects in Apache.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top