Mobile app version of vmapp.org
Login or Join
Carla537

: Forcing SSL and www in .htaccess I'm looking for a way to force SSL and www. I've been able to force both separately but together I keep running into redirection issues. The following code

@Carla537

Posted in: #Apache #Htaccess #Https #ModRewrite #Redirects

I'm looking for a way to force SSL and
I've been able to force both separately but together I keep running into redirection issues. The following code works when handling a URL in this format: example.com and properly redirects to www.example.com but when the incoming URL is example.com it will not forward to www.example.com - Any suggestions?

EDIT: it should also send www.example.com to www.example.com.
RewriteCond %{REMOTE_ADDR} !127.0.0.0
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} !^www.example.com$
RewriteRule ^(.*)$ www.example.com/ [R,L]

10.05% popularity Vote Up Vote Down


Login to follow query

More posts by @Carla537

5 Comments

Sorted by latest first Latest Oldest Best

 

@YK1175434

Just implemented this for my site. Works like a charm!
Added to the top of my .htaccess file.
Redirects all instances of people typing www or not www, http or https.

# BEGIN HTTPS Redirect
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ www.example.com/ [R,L]
# END HTTPS Redirect

10% popularity Vote Up Vote Down


 

@Angela700

You could also use the following lines that I use and work flawlessly.

(Remove the top RewriteCond if you do not use CloudFlare)

RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' [OR]
RewriteCond %{HTTPS} off
RewriteRule .* %{HTTP_HOST}%{REQUEST_URI} [L,R=302]
RewriteCond %{HTTP_HOST} !^www.
RewriteRule .* www.%{HTTP_HOST}%{REQUEST_URI} [L,R=302]

10% popularity Vote Up Vote Down


 

@Fox8124981

The first line is used to prevent internal URL's from being rewritten. That might cause different pages to be displayed, so I've removed it.

If the host is example.com or is not requested over HTTPS, it will be rewritten to example.com/. I.e., it rewrites example.com, www.example.com and example.com to www.example.com in one action.

RewriteCond %{HTTP_HOST} ^example.com$ [OR]
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$ www.example.com/ [R,L]


Documentation on mod_rewrite for Apache 2.2.

If you've subdomains like forum.example.com, the first rule should be as is. Otherwise, you can do a negative match against example.com as well.

10% popularity Vote Up Vote Down


 

@Berryessa370

Try this:

RewriteCond %{REMOTE_ADDR} !127.0.0.0
RewriteCond %{SERVER_PORT} 80 [OR]
RewriteCond %{HTTP_HOST} !^www.example.com$
RewriteRule ^(.*)$ www.example.com/ [R,L]

10% popularity Vote Up Vote Down


 

@Samaraweera270

Doesn't the third line have to be:

RewriteCond %{HTTP_HOST} ^example.com$

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme