Apache Responds with Wrong Certificate

I ran into a situation where a client was accessing a test site and ended up getting a certificate from another site on the same server. Here is the setup:

All virtual hosts are on the same IP address as the SSL site is on so I have this in httpd.conf:


The problem is this: Apache must create the SSL connection BEFORE the host header is received. When it receives a request on, it uses the cert attached to that virtual host BEFORE the web site is presented. So if you attempt to connect to a non-ssl site on HTTPS, apache sends you the cert for the SSL site and then serves up the web site of the non-ssl virtual host. At this point, the user gets a browser error! YUCK!

The solution: mod_rewrite!
In the virtual host configuration for the SSL site, put these rules:

# SERVER_HOST <> https://ssl.example.com
RewriteCond %{HTTP_HOST} !^ssl\.example\.com$ [NC,OR]
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^.*$ https://ssl.example.com%{REQUEST_URI} [L,R]

The first RewriteCond checks the hostname in the header in the request.
The second RewriteCond checks the port number of the request.
The RewriteRule then sends the user's browser to the proper port with the proper hostname.


Submitted by davea on Tue, 2008-07-01 23:17. categories [ ]