force SSL and no WWW on Apache

2.8k Views Asked by At

I'm having trouble coming up with the proper syntax to accomplish both forcing the SSL and no WWW.

EDIT

I've been able to accomplish each task separately but when combining the two i find myself stuck in a redirection loop.

working syntax to force no WWW:

RewriteCond %{HTTP_HOST} !^domain\.com$
RewriteRule (.*) http://domain.com/$1 [R=301,L]

My attempt to force no WWW and SSL

RewriteCond %{SERVER_PORT} !^443$
RewriteCond %{HTTP_HOST} !^domain\.com$
RewriteRule (.*) https://domain.com/$1 [R=301,L]

Thanks for any suggestions!

4

There are 4 best solutions below

0
On BEST ANSWER

For SSL you could use something like:

Redirect / https://domain.com/

Place this only in the section of your virtual host you configure for HTTP, not HTTPS, to not run clients into endless loops.

10
On

By 'no WWW' I assume you mean you want to remove any 'WWW.' prefix of the hostname? Try this:

RewriteCond "%{HTTP_HOST}" "^(?:www\.)?(.*)"  [NC]
RewriteCond "%{HTTPS}"     "=on"
RewriteRule "(.*)"         "https://%1$1"     [R=301,L]

If you're doing this in a .htaccess file, change that last line to

RewriteRule "(.*)"         "https://%1/$1"    [R=301,L]

If you want to be able to remove the 'WWW.' prefix regardless of SSL-ness or not, try this:

RewriteCond "%{HTTP_HOST}" "^(?:www\.)?(.*)"  [NC]
RewriteCond "%{HTTPS}"     "=on"
RewriteRule "(.*)"         "https://%1/$1"    [R=301,L]

RewriteCond "%{HTTP_HOST}" "^(?:www\.)?(.*)"  [NC]
RewriteRule "(.*)"         "http://%1/$1"     [R=301,L]
3
On

Here's what I'm using on one of my sites - it seems to work a little better than most of the other methods I've seen:

  # The code below tells apache to always require secure (ssl/tls) connections
  # to the website. If a client tries connecting over port 80 (http://),
  # then the client will be redirected to https:// (over port 443).
  RewriteCond %{REMOTE_ADDR} !127\.0\.0\.0
  RewriteCond %{SERVER_PORT} 80
  RewriteRule ^(.*)$ https://example.com/$1 [R,L]

For the no-www rule, check out the .htaccess files on any open-source CMS, like Drupal or Wordpress, to see some of the best practices.

0
On

I found this to work for a couple of my client sites:

# Force SSL
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule (.*) https://%1%{REQUEST_URI} [L,R=301]

# Rewrite all http to https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}