HTTPS Force Redirect
Luke Hebert
- 2 minutes read - 408 wordsIf you are running a site behind Apache and want to make sure every visitor lands on an encrypted connection, a three-line mod_rewrite block in your .htaccess file does the job. No extra modules, no server-level config changes, just a redirect that fires the moment a request arrives over plain HTTP.
The Rewrite Rules
Add the following to your site’s .htaccess file (or to a <Directory> block in your Apache virtual host config):
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]Here is what each line does:
RewriteEngine Onenables the mod_rewrite engine for this directory.RewriteCond %{HTTPS} offchecks whether the incoming request is not already using HTTPS. If it is, the rule below is skipped.RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]captures the full path, rebuilds the URL with thehttpsscheme, and issues a 301 permanent redirect. TheLflag stops further rule processing.
Where to Put It
- Per-site: drop it into the
.htaccessfile in your document root. - Server-wide: place it inside a
<Directory>or<VirtualHost>block in your Apache config and runapachectl configtestbefore reloading.
Things to Watch
Use a 301 redirect only once you are confident the HTTPS endpoint is stable. A 301 is cached aggressively by browsers and CDNs, so switching back to HTTP later will not take effect until those caches expire. If you are still testing, swap R=301 for R=302 (temporary redirect) and change it back when you are ready.
- Make sure
mod_rewriteis actually loaded (a2enmod rewriteon Debian/Ubuntu, or checkhttpd -Mon RHEL). - If you are behind a reverse proxy (HAProxy, Nginx, a load balancer), the
%{HTTPS}variable may reportoffeven when the original request was TLS-encrypted. In that case, add aRewriteCond %{HTTP:X-Forwarded-Proto} !=httpscondition before the rule so the proxy’s header is respected. - Verify that your SSL/TLS certificate is valid and that port 443 is open in your firewall before deploying the redirect, or you will lock yourself out of the site.
Quick Verification
After deploying, run:
curl -I http://yourdomain.comYou should see a 301 Moved Permanently response with a Location: https://yourdomain.com header. Then follow the redirect:
curl -I -L http://yourdomain.comThe final response should be a 200 OK over HTTPS. If you see a redirect loop, double-check that the RewriteCond is correctly detecting the protocol.
That is all there is to it. Three lines, one redirect, and every visitor is on an encrypted connection from that point forward.