I have an SSL certificate being only valid for example.com (not valid for subdomains) and therefore want to redirect both http://example.com and http://www.example.com to https://example.com using nginx. My config file starts as follows:
server {
# This should catch all non-HTTPS requests to example.com and *.example.com
listen 80;
server_name example.com www.example.com;
access_log off;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
# Actual server config starts here...
However, the redirection does not work as desired. Requesting http://example.com leads correctly to https://example.com, but http://www.example.com will be redirected to https://www.example.com which yields an SSL error as my certificate is not valid for subdomains. I'm aware that there is no possibility of redirecting from invalid HTTPS to valid HTTPS, but I at least want to achieve a redirect from HTTP to HTTPS because users still tend to type in www. in the browser.
When I wget --spider www.example.com
, it returns the correct result:
Spider mode enabled. Check if remote file exists.
--2015-03-19 02:22:47-- http://www.example.com/
Resolving www.example.com (www.example.com)... ***.***.***.***
Connecting to www.example.com (www.example.com) **** connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://example.com/ [following]
Spider mode enabled. Check if remote file exists.
--2015-03-19 02:22:47-- https://example.com/
...
But for some reason, browsers end up requesting https://www.example.com rather than https://example.com. I already tried from multiple browsers and computers. Where is my mistake? The whole first server block in the config file seems to be completely ignored - if I delete it, the browser shows the exact same behaviour (with disabled DNS cache), whereas the output of wget --spider
changes consistently.
https://www
redirect - otherwise it's browser cache of some form.