This guide explains how to configure .htaccess
rewrite rules to force all visitors to use HTTPS and the non-www version of your website. It also includes examples for exceptions.
📌 Requirements
- Apache web server with
mod_rewrite
enabled .htaccess
file located in your document root (typically/public_html
or/home/user/public_html
)- SSL certificate installed and working for your domain
🔁 Basic Rule: Redirect WWW to non-WWW with HTTPS
This rule:
- Redirects all
http://
andhttp://www.
tohttps://
- Removes
www.
from the domain
RewriteEngine On
# Redirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
# Redirect HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
🌐 Alternate Rule: Redirect HTTP to HTTPS + Force www
If you want to force the www version (opposite of the previous example):
RewriteEngine On
# Redirect to www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
# Redirect HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
🚫 Exception: Skip HTTPS Redirect for Specific Directory
This rule forces HTTPS on everything except a specific directory, e.g. /dir1/dir2/dir3/
:
RewriteEngine On
# Redirect everything to HTTPS except for /dir1/dir2/dir3/
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/dir1/dir2/dir3/
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
✅ Testing
After setting up your rules:
- Clear browser cache
- Visit:
http://www.example.com
➝ should redirect tohttps://example.com
http://example.com
➝ should redirect tohttps://example.com
- Visit your exception directory (if configured) to ensure it doesn’t redirect to HTTPS.
📝 Notes
- Use
[R=301,L]
for permanent redirects (best for SEO). Use[R=302,L]
for testing to avoid browser caching. - Always backup your
.htaccess
before making changes. - You can combine or chain rules as long as the order makes logical sense.