7

There's a few similar questions which I tried to work out the answer from, but so far I have been unsuccessful. Please advise how I can always redirect http to https (and also remove www. from the hostname in the process). Also a side note, it would be nice to do this inside the main Apache conf rather than .htaccess - but I imagine this will not apply to most people.

Update:

I've added this snippet to a VirtualHost section:

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

... but it has no effect when I access http://www.domain (it should redirect to https://domain)

Update 2:

It had no effect because I did not use RewriteEngine on - so it works now:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]
Nick Bolton
  • 5,186

5 Answers5

18

There are so many solutions:

RewriteEngine On
RewriteCond %{HTTPS} !^on$
RewriteRule (.*) https://yourdomain/$1 [R,L]
5

If you're using a load balancer you'll need to use a different conditional. This works for AWS ELB:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteRule (.*) https://yourdomain.com/$1 [R=301,L]
</IfModule>
Chief
  • 151
4

two solutions . add either of them to your .htaccess

RewriteEngine on
RewriteCondition %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L] 

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
3

I wouldn't use mod_rewrite, you can achieve it simply with mod_alias:

Redirect permanent / https://other-site

Where 'other-site' is the hostname you want to redirect to, ommitting the www. prefix that you do not want.

jmtd
  • 575
1

From your comments, it sounds like you're not including mod_rewrite:

LoadModule rewrite_module modules/mod_rewrite.so