2

I've looked at many SE threads and done various google searches and can't figure out why i can't redirect www.mysite.com to mysite.com on my nginx server.

The 1st server block does the http://mysite.info -> https://mysite.info redirect as you'd expect. So i'm not sure why the 2nd server block isn't doing the same for the www.mysite.info -> mysite.info.

Here's the relevant part of my nginx.conf file:

server {
    server_name mysite.info;
    rewrite ^ https://$server_name$request_uri? permanent;
}

server {
    server_name www.mysite.info;
    rewrite ^ https://mysite.info$request_uri? permanent;
}

server {
    listen   443;
    ssl    on;
    server_name mysite.info;
    # other directives, handling PHP, etc.
}

Any thoughts on what's going wrong?

1 Answers1

7

You're redirecting to $server_name, which is www.mysite.info in the second server block - so all that's doing is redirecting to HTTPS, not changing the host.

rewrite ^ https://mysite.info$request_uri? permanent;

That'll handle the change in host as well as the change to HTTPS.

If you wanted the redirect to be protocol agnostic, a better approach would be:

rewrite ^ $scheme://mysite.info$request_uri? permanent;

On recent versions of nginx, this works as well (and should be a bit faster):

return 301 $scheme://mysite.info$request_uri;
Shane Madden
  • 115,228