How to 301 redirect IP to domain? Basically my site is accessible from abc.com and the relevant ip on which it is pointing

February 17, 2017 281 views
Nginx Ubuntu 16.04

I have read major tutorials and questions on how to 301 redirect the ip to my main domain but everything seems irrelevant - either I couldnt locate the relevant lines to be changed or the versions of ubuntu are different. Any help here is appreciated?

1 Answer
UKn0Me February 17, 2017
Accepted Answer

Create a default server block if you haven't got one already with

server {
    listen 80 default_server;
    return 301 http://abc.com/;
}

If you already have a default server block, all you have to add is the return line.

This will redirect any requests that do not match a configured virtual host (server block in nginx)

  • Thanks @UKn0Me

    I tried editing this "sudo nano /etc/nginx/sites-available/default" location - but then website stopped loading.

    Error dispalyed in chrome was "Website redirecting too many times"

    • You've likely put the return line into the server block for your domain, where server_name abc.com; would be. If you're using the provided server block for your site, you'll want to create a new one, as outlined above.

      • I have these settings :
        server_name XX.XX.XX.XX (IP of the Server)

        And I have put the 301 line in the server block where it is as follows:
        server {
        listen 80 defaultserver;
        listen [::]:80 default
        server;
        return 301 http://abc.com/;

        ....
        }

        I think the server_name should not be the IP but my actual domain name (abc.com) is it?

        • That would be correct, you would want something like this;

          server { # The default server block
              # By default, requests will go here if they don't
              # match another server block, redrecting them.
          
              listen 80 default_server; 
              return 301 http://abc.com/;
          }
          
          server { # Your site's server block
              # Requests to your domain will reach
              # this server block, and will not be redirected.
          
              listen 80;
              server_name abc.com;
          
              # Your site's configuration...
          }
          
Have another answer? Share your knowledge.