Nginx 302 redirect only naked IP

301-redirectanycastnginx

I'm trying to setup a 302 redirect if someone enters the IP address, but 301 all other requests to the www.subdomain of that domain.

server {
    listen 198.251.86.133:80;
    server_name 198.251.86.133;
    return 302 http://www.jacobdevans.com/anycast-301/;
}

server {
    listen 198.251.86.133:80;
    server_name _;
    return 301 http://www.$host$request_uri;
}

I have the 301 working, except if I put the 302 section above in, my hope is to allow anyone (non-https, sorry) to be able to point their A record root domain somewhere easy to do 301, example.com to www.example.com

Currently, everything is caught by the first listen option

# curl -I jacobdevans.com
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.6.3
Date: Mon, 28 Sep 2015 20:08:45 GMT
Content-Type: text/html
Content-Length: 160
Connection: keep-alive
Location: http://www.jacobdevans.com/anycast-301/

# curl -I 198.251.86.133
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.6.3
Date: Mon, 28 Sep 2015 20:08:56 GMT
Content-Type: text/html
Content-Length: 160
Connection: keep-alive
Location: http://www.jacobdevans.com/anycast-301/

http://www.redirect-checker.org will pull from my luxembourg location

Thanks!

Best Answer

You would need to have a single server block as both will not be read while they match the same listen directive.

You should be able to modify the blocks as follows to acheive your desired results:

server {
   listen 80;
   server_name 198.251.86.133;
   return 302 http://www.jacobdevans.com/anycast-301/;
}

server {
   listen 80 default_server;
   return 302 http://www.$host$request_uri;
}

Setting the default_server and allowing that block to be the 'catch all' while explicitly defining the IP to match the incoming HOST header will result in all requests for the direct IP being redirected to http://www.jacobdevans.com/anycast-301/ and the rest to http://www.$host$request_uri.

Related Topic