Mobile app version of vmapp.org
Login or Join
Sherry384

: Htaccess redirect non-www to www with SSL/HTTPS I want a rewrite rule that redirects everything to https:// AND www. For example https://example.com should be going to https://www.example.com This

@Sherry384

Posted in: #Apache #Htaccess #Https #ModRewrite

I want a rewrite rule that redirects everything to AND
For example example.com should be going to www.example.com
This is what I have:

RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteCond %{HTTP_HOST} ^(www.)?example.com$ [NC]
RewriteRule ^(.*)$ "https://www.example.com/" [R=301,L]

10.03% popularity Vote Up Vote Down


Login to follow query

More posts by @Sherry384

3 Comments

Sorted by latest first Latest Oldest Best

 

@Steve110

This will use for both www or non-www
If you try to open link with www then url redirect to https with www


Example: domain.com redirect to domain.com

or If you try to open link with non-www then url redirect to https with non-www


Example: www.domain.com redirect to www.domain.com

RewriteEngine on

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ %{HTTP_HOST}%{REQUEST_URI} [R=301,L]

10% popularity Vote Up Vote Down


 

@Sherry384

I found the solution.

RewriteCond %{HTTPS} off
RewriteRule .* %{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www.
RewriteRule .* www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

10% popularity Vote Up Vote Down


 

@Jamie184

Your conditions are implicitly AND'd and your second condition will always be true (unless you have other domains), so your current rules will only redirect non-SSL traffic.

You need to OR the conditions and negate the www (second) condition:

RewriteEngine On
RewriteCond %{SERVER_PORT} !=443 [OR]
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ www.example.com/ [R=301,L]


If the SERVER_PORT is not 443 (ie. is not HTTPS) or the host does not start with (ie. you are accessing the bare domain) then redirect to the canonical URL.

However, whether this will redirect example.com to www.example.com will depend on your security certificate. (Your site needs to be accessible by both www and non-www over SSL for the .htaccess redirect to trigger.)

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme