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?

tim peterson
  • 693
  • 2
  • 9
  • 18

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
  • 114,520
  • 13
  • 181
  • 251
  • 2
    Also, [according to NGiNX's documentation](http://wiki.nginx.org/Pitfalls), it is better practice to use `return 301` instead of `rewrite`. – tacotuesday Aug 27 '12 at 23:38
  • @Shane, sorry I made a copy/paste mistake. My 2nd directive is as you've written in your answer. Please see my updated question. Thoughts on why that doesn't work? – tim peterson Aug 27 '12 at 23:55
  • @Shane, also how use the `return 301` given my 3 `server{}` blocks? I've just tried a couple things but get this error: ` invalid number of arguments in "return" directive` when I try to restart my server. – tim peterson Aug 28 '12 at 00:01
  • @timpeterson Do you have any _other_ `server` blocks? – Michael Hampton Aug 28 '12 at 00:02
  • none that i know of, i'm a novice as you can tell, just did the `sudo apt-get install nginx /php` on my ubuntu machine and now here I am, are there other files I need to look at? – tim peterson Aug 28 '12 at 00:04
  • I have 2 include statements in my `http{}` block that were there by default: `include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*;`. Should I comment these out? – tim peterson Aug 28 '12 at 00:06