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

February 17, 2017 2k views
Ubuntu 16.04 Nginx

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?

2 Answers

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

server {
    listen 80 default_server;
    return 301;

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; 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
        return 301;


        I think the server_name should not be the IP but my actual domain name ( 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;
          server { # Your site's server block
              # Requests to your domain will reach
              # this server block, and will not be redirected.
              listen 80;
              # Your site's configuration...

Man, you saved my life too. Thank You so much!!!!!

Have another answer? Share your knowledge.