apache redirect in https from none www to www domain

123 views Asked by At

Edit: Redirect permanent "/" "https://%{HTTP_HOST}/" actually doesn't work in the first redirect. It appeared to work because my CDN automatically redirected http to https:, not because of my settings. Sorry for the confusion.


I am trying to write Apache httpd config file to redirect all http traffic to https, and also need to redirect none www domain to www.

for example
http://example.com http://www.example.com https://example.com
should all be redirected to
https://www.example.com

Here is what I did:

<VirtualHost ipaddress:80>  
  ServerName example.com  
  ServerAlias www.example.com  

  Redirect permanent "/" "https://%{HTTP_HOST}/"
</VirtualHost>

This part works. All http is redirect to https. Note, the %{HTTP_HOST} is resolved and replaced. Now I need to redirect none www to www

<VirtualHost ipaddress:443>
  SSLEngine on
  ServerName www.example.com
  ServerAlias example.com

  <If "%{HTTP_HOST} !~ /www/">
     Redirect permanent "/" "https://www.%{HTTP_HOST}/"
  </If>

  ...
</VirtualHost>

When I visit https://example.com it redirects but this time it is redirected to https://www.%{HTTP_HOST}/ instead of https://www.example.com/.

Now if I use
Redirect permanent "/" "https://www.example.com/"
then https://example.com will be redirected to https://www.example.com

So it appears that the %{HTTP_HOST} was not replaced in the second VirtualHost block.

How to make it correct?

1

There are 1 answers

0
Edward Romero On

You could try using a rewrite rule

 RewriteEngine On
 RewriteCond %{HTTP_HOST} ^https://example.com [NC]
 RewriteRule ^(.*)$ https://www.example.com/$1