My shared hosting uses Apache. I want every request to end up at https://example.com with no www and no redirect chain. What rules should I use?
DEV3 Developer Forum
How do I redirect HTTP to HTTPS and non-www to www with Apache .htaccess?
Every post is reviewed first. Usually reviewed within 24 hours.
1 reply
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
.htaccessis ignored unless the virtual host hasAllowOverride All(or at leastFileInfo).mod_rewritemust 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.comrather 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.