NGINX how to redirect accesses by IP to access by host name instead?

13,343

Solution 1

Add another server block to your config file

server {
    listen 180.10.1.1:80;
    server_name 180.10.1.1;
    rewrite .* http://www.mysite.com$request_uri permanent;
}

Solution 2

if you have latest version of nginx:

server {
  listen 80 default;
  rewrite ^ http://mysite.com$request_uri permanent;
}

Solution 3

The above 2 answers didn't work for me either and resulted in an infinite redirect loop. Adding the ip address to my server_name worked:

server {
    listen 80;
    server_name mydomain.com www.mydomain.com 67.20x.xxx.xx;
       ...
    }
Share:
13,343

Related videos on Youtube

Admin
Author by

Admin

Updated on September 17, 2022

Comments

  • Admin
    Admin almost 2 years

    Somehow, Google has indexed my site via IP address as well as by domain. E.g., 180.10.1.1/index.php as well as www.mysite.com/index.php

    I want to 301 all those ip address urls to the appropriate hostname urls, but can't figure out how to do it in nginx.conf.

    Thank you for your help...

    • Admin
      Admin over 12 years
      Neither of these answers work for me with the latest version of nginx. I just end up in an infinite redirect loop. I've even tried to regex the IP hoping it would stop future requests but to no avail.