Apache rewrite redirect to https and www

Posted on

Apache rewrite redirect to https and www – Managing your servers can streamline the performance of your team by allowing them to complete complex tasks faster. Plus, it can enable them to detect problems early on before they get out of hand and compromise your business. As a result, the risk of experiencing operational setbacks is drastically lower.

But the only way to make the most of your server management is to perform it correctly. And to help you do so, this article will share nine tips on improving your server management and fix some problem about apache-2.2, mod-rewrite, rewrite, , .

I need to get mod_rewrite to do the following

http://abc.com -> https://www.abc.com
https://abc.com/login -> https://www.abc.com/login
http://www.abc.com?x=3 -> https://www.abc.com?x=3
https://abc.com/login?x=1 -> https://www.abc.com/login?x=1
http://www.abc.com/login?x=3 -> https://www.abc.com/login 

I have the following, in my abc.com.conf vhost file but its not work correctly

<VirtualHost  *:80>
ServerName abc.com
ServerAlias www.abc.com        

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

RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.abc.com/%{REQUEST_URI}

</VirtualHost>

<VirtualHost  *:443>
ServerName abc.com
ServerAlias www.abc.com        

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


 </VirtualHost>

Can anyone help me out on the rest?

[edited to clarify]

Solution :

First of all it looks like you want to force ssl for all.. I would take care of that first in your *:80 block:

<VirtualHost *:80>

  ServerName abc.com
  ServerAlias www.abc.com        

  Redirect permanent / https://www.abc.com/

</VirtualHost>

Then do your *:443 .. However you can make it real easy and just pull out abc.com into a separate vhost:

NameVirtualHost *:80
NameVirtualHost *:443

<VirtualHost *:80>
  ServerName abc.com
  Redirect permanent / https://www.abc.com/
</VirtualHost>

<VirtualHost *:443>
  ServerName abc.com
  Redirect permanent / https://www.abc.com/
   ....
    ...
   # Note you need a wildcard cert.. I assue you have one already or are using self signed. 
</VirtualHost>

Ok now you redirected all your abc.com to www.abc.com and you can set up this vhost as usual without all the rewrites.

<VirtualHost *:80>

  ServerName www.abc.com        
  Redirect permanent / https://www.abc.com/
</VirtualHost>

<VirtualHost *:443>
  ServerName www.abc.com
  ...
   ....
</VirtualHost>

Leave a Reply

Your email address will not be published.