Ensuring your website loads consistently with HTTPS and your preferred domain format improves security, SEO, and user experience. This guide explains how to configure these redirects using .htaccess on Apache or LiteSpeed servers.
The .htaccess file is located in your website's root directory (typically public_html or www). If the file doesn't exist, you can create one.
This redirects all HTTP traffic to HTTPS while preserving the existing WWW or non-WWW format:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Use this if you want your site to always load as https://www.example.com:
RewriteEngine On
# Redirect to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Redirect to WWW
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Use this if you want your site to always load as https://example.com:
RewriteEngine On
# Redirect to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Redirect to non-WWW
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [L,R=301]
The examples above may cause two separate redirects (one for HTTPS, one for WWW). For better performance, you can combine them into single-pass rules.
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.example.com%{REQUEST_URI} [L,R=301]
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ https://example.com%{REQUEST_URI} [L,R=301]
Replace example.com with your actual domain name when using these combined rules.
Add these rules near the top of your .htaccess file, after RewriteEngine On but before any CMS-specific rules. If you're using WordPress or another CMS, place the redirect rules above the existing block that typically begins with # BEGIN WordPress.
If your site gets stuck in a redirect loop, your server may be behind a proxy or load balancer that handles SSL termination. Try this alternative approach:
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
This usually indicates a syntax error in your .htaccess file. Restore your backup and carefully re-add the rules, checking for typos or missing characters.
After implementing your rules, test all four variations of your URL:
All four should redirect to your preferred format. You can use online redirect checker tools to verify the redirects are working and returning 301 (permanent) status codes.