📘Redirect non-WWW to WWW with SSL (HTTPS)

This guide explains how to force non-WWW to WWW redirects with HTTPS enabled using Apache .htaccess rewrite rules. These rules are commonly used by web hosts to enforce consistent, secure URLs.


1. Standard .htaccess Rule to Redirect non-WWW to WWW with HTTPS

Place this code inside the .htaccess file in the root of your website (/public_html/.htaccess on cPanel-based servers):

RewriteEngine On

# Redirect to HTTPS if not already
RewriteCond %{HTTPS} off [OR]

# Redirect to WWW if not already
RewriteCond %{HTTP_HOST} !^www\. [NC]

# Perform redirect
RewriteRule ^(.*)$ https://www.hostxnow.com%{REQUEST_URI} [L,R=301]
  • Replace www.hostxnow.com with your actual domain name.
  • This handles both:
    • Non-HTTPS → HTTPS
    • Non-WWW → WWW

2. Alternative Method (Simplified)

RewriteEngine On

# Redirect all HTTP to HTTPS and force WWW
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Note: This assumes the user is accessing a non-WWW domain and appends www. to %{HTTP_HOST}. It may not always behave correctly if already accessing via www. — so it’s less precise.


3. Custom Exception Example (Skip Specific Directory)

If you want to redirect everything except a specific directory (e.g. /dir1/dir2/dir3/), use:

RewriteEngine On

# Skip redirect for specific path
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/dir1/dir2/dir3/
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

You can combine this logic with a WWW enforcement rule as needed.


4. Testing & Validation

  • After updating .htaccess, clear browser cache or test in incognito.
  • Use tools like https://redirect-checker.org/ to verify:
    • HTTP → HTTPS
    • non-WWW → WWW
    • Custom exclusions working

References

Scroll to Top