title: Rewrite - forward server IP to domain url nginx
body: <p>I'd like to have the IP of my server be rewritten as a domain name url but I'm having the hardest time figuring out how to make this happen.  </p>
  
  <p>For example, when I enter 213.34.54.xxx in the browser, I'd like it to be rewritten as mydomain.com and NOT display the IP address.</p>
  
  <p>My current configuration is as follows:</p>
  
  <p><strong>/etc/nginx/nginx.conf</strong></p>
  
  <pre><code>user www-data;
  worker_processes 2;
  error_log  /var/log/nginx/error.log;
  pid /var/run/nginx.pid;
  
  events {
    worker_connections 1024;
  }
  
  http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    access_log /var/log/nginx/access.log;
    server_names_hash_bucket_size 64;
    sendfile        on;
  
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/mydomain;
  }
  </code></pre>
  
  <p><strong>/etc/nginx/sites-enabled/mydomain</strong></p>
  
  <pre><code>upstream unicorn {
      server unix:/tmp/unicorn.mydomain.sock fail_timeout=0;
     }
  
      server {
        listen 80 default;
        server_name localhost;
        root /home/deployer/apps/mydomain/current/public;
  
        location ^~ /assets/ {
          gzip_static on;
          expires max;
          add_header Cache-Control public;
        }
  
        try_files $uri/index.html $uri @unicorn;
        location  / {
          proxy_set_header Host $http_host;
          proxy_set_header  X-Real-IP  $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Host $http_host;
          proxy_redirect off;
          proxy_pass http://unicorn;
        } 
  
        error_page 500 502 503 504 /500.html;
        client_max_body_size 4G;
        keepalive_timeout 10;
       }
  </code></pre>
  
  <p>I've tried adding this to the server directive in <strong>mydomain</strong> configuration file:</p>
  
  <pre><code>rewrite ^ $scheme://mydomain.com$request_uri redirect;
  </code></pre>
  
  <p>but I get a TOO MANY REDIRECTS ERROR in my browsers.</p>
  
  <p>At the very least, I'm able to prevent the IP address from being displayed by using this in the server directive:</p>
  
  <pre><code>if ($host !~* ^www\.) {
      rewrite ^(.*)$ http://www.$host$1 permanent;
     }
  </code></pre>
  
  <p>However, this is listed as one of the pitfalls on the nginx site :(</p>
  
  <p>Any insights of what I might be doing wrong would be GREATLY appreciated!</p>
  
  <p>Thanks!</p>