NGINX redirect all domains to one, but not server’s own public and private IP addresses

configurationload balancingnginxredirectrewrite

I haven't been able to find a question that matches my particular scenario so, hopefully this isn't a duplicate, if so I apologize.

I have 4 web servers behind a load balancer. I want only www.mydomain.com, 123.123.123.123 (my server's public IP address) and 456.456.456.456 (my server's internal network IP address) to work, anything else should redirect to www.mydomain.com.

Why: I need to send everything to www.mydomain.com because we have had people setting up other domains (www.otherdomain.com) pointing to our IP address, so it acts like a mirror of our site. We don't know why they do this but Google starts crawling their site as if it was a different site entirely and it causes trouble. I need to allow the server's IP addresses through because we use that for internal server chatter via a custom API, to get around the load balancer.

The only solutions I've been able to find either redirect everything INCLUDING the IP addresses to www.mydomain.com, or they end up redirecting nothing.

Here is my current config (truncated for simplicity):

server {
    listen 80;
    server_name www.mydomain.com 123.123.123.123 456.456.456.456;
}

server {
    listen 80 default;
    server_name _;
    rewrite ^ http://www.mydomain.com$request_uri?;
}

Expected: Requests to the correct domain, or either IP address, match the first rule. All other requests match second rule and get redirected. Actual: Nothing gets redirected at all, I'm assuming because NGINX is just matching the IP address regardless of domain to the first rule. It could also possibly be that the load balancer is messing it up? I am using a Rackspace cloud load balancer, if that helps.

I've also tried this config:

server {
    listen 80 default;
    server_name www.mydomain.com;
}

server {
    listen 80;
    server_name _;
    rewrite ^ http://www.mydomain.com$request_uri?;
}

This has the same results as the previous. Nothing seems to get redirected.

Any ideas how I can fix this?

Thanks for your help!

Best Answer

I got it working. Sameer was close but I'm not sure he understood my exact question. This is the solution to my problem;

server {
    listen 80;
    server_name www.mydomain.com 123.123.123.123 456.456.456.456;
}

server {
    listen 80 default_server;
    server_name _;
    rewrite ^ http://www.mydomain.com$request_uri?;
}

With the above, you can load the site via www.mydomain.com, or the direct internal and public IP addresses, but if you try to load it any other way you get redirected.

Oddly enough... This is the first example I tried above. I don't know why it didn't work then and it working now. Perhaps because the "listen 80 default" has been deprecated in favor of "listen 80 default_server". Or perhaps I confused things will testing across all 4 nodes. Either way, it seems to be working right now with this definition!