DEV3 Technologies home

DEV3 Developer Forum

How do I redirect HTTP to HTTPS and non-www to www with Apache .htaccess?

DevOps helpSolved0 views

1 reply

dev3 · Accepted answer

Use one rule set so every variant redirects directly to the final URL in a single 301 hop.

RewriteEngine On

# Force HTTPS and www in one step
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]

Place it above any WordPress or framework rewrite block. For the opposite direction (force non-www), set the host condition to ^www\.example\.com$ and the target to https://example.com%{REQUEST_URI}. The original query string is appended automatically.

Behind a proxy or CDN (Cloudflare, load balancer) Apache may always see HTTP. Check the forwarded header instead:

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]

If it does not work

  • .htaccess is ignored unless the virtual host has AllowOverride All (or at least FileInfo).
  • mod_rewrite must be enabled: sudo a2enmod rewrite && sudo systemctl restart apache2.
  • A redirect loop means the app also forces a scheme, or the proxy hides HTTPS; use one source of truth.
  • Browsers cache 301 redirects hard, so test with curl -I http://example.com rather than the browser.

If you control the server config, a <VirtualHost *:80> containing Redirect permanent / https://www.example.com/ is faster than .htaccess since Apache does not scan override files on every request.

For other rules (caching, compression, blocking), the htaccess generator builds tested snippets.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.