HTTP to HTTPS redirect even for IP

apache-2.4httphttpsredirectrewrite

I have already read many question on basic http -> https redirection, but it all talks about the redirect/rewrite including only domain name.

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

For eg this above snippet will redirect all request to http:www.example.com to https:www.example.com
This ofcourse is the apache recommended way.

But how would we redirect http to https even if request is based on IP.
Like http:ip to https:ip How can this be achieved?
I know that https is for domain name, but I have this particular requirement of client being able to access over IP as well.

Best Answer

Requests using the ip-address (or HTTP 1.0 requests without a Host: header) and those for unknown domains are handled by the default VirtualHost which defaults to the first VirtualHost entry unless explicitly defined with:

<VirtualHost _default_:*>
    Redirect / https://www.example.com/
    ...
</VirtualHost>

So depending on your current configuration:

  • you may not need to do anything to handle requests using the ip-address (i.e. when you only have a single VirtualHost or the www.example.com is already the first entry)
  • or you can re-order the current VirtualHost entries so that www.example.com becomes the first VirtualHost entry
  • explicitly define the _default_:80 VirtualHost