I have a website, say www.foo.com with an IP address 126.96.36.199 I have an SSL certificate for www.foo.com and when I visit https://www.foo.com all is good. However if I visit https://188.8.131.52 it says the certificate is invalid, which is fair enough. Is there any way to get https://184.108.40.206 to redirect to https://www.foo.com using apache2 or am I stuck with it having a certificate error?
No you can't redirect https without first getting the "Invalid Certificate" error if the certificate doesn't match to domain name used (in this case it's the IP 220.127.116.11 since it is manually entered).
You can redirect http://18.104.22.168 without this problem because there is no SSL handshake. But if you specify https this requires the use of SSL which in turn returns the "Invalid Certificate" error as there is no way to validate the SSL handshake.