重写 - 将服务器IP转发到域url nginx

Joh*_*ohn 6 ip forwarding nginx unicorn

我想将我的服务器的IP重写为域名网址,但我正在努力弄清楚如何实现这一目标.

例如,当我在浏览器中输入213.34.54.xxx时,我希望将其重写为mydomain.com并且不显示IP地址.

我目前的配置如下:

/etc/nginx/nginx.conf

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;
}
Run Code Online (Sandbox Code Playgroud)

在/ etc/nginx的/启用的站点 - /MYDOMAIN

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;
     }
Run Code Online (Sandbox Code Playgroud)

我已经尝试将此添加到mydomain配置文件中的server指令:

rewrite ^ $scheme://mydomain.com$request_uri redirect;
Run Code Online (Sandbox Code Playgroud)

但是我的浏览器中出现了太多的REDIRECTS ERROR.

至少,我能够通过在server指令中使用它来阻止显示IP地址:

if ($host !~* ^www\.) {
    rewrite ^(.*)$ http://www.$host$1 permanent;
   }
Run Code Online (Sandbox Code Playgroud)

但是,这被列为nginx网站上的陷阱之一:(

任何关于我可能做错的见解都会非常感激!

谢谢!

Gui*_*son 11

实际上上面的答案不起作用(至少对我而言).我想,既然问题已经提出,提问者找到了他的解决方案,但是因为我在google上搜索了很多链接,所以这个解决方案可以帮助其他人,只需将其添加到你的conf文件中:

server {
        server_name 162.13.171.178;
        # you can add other server_name if you need other IPs
        # or domain names such as without the www

        add_header X-Frame-Options "SAMEORIGIN";

        return 301 $scheme://www.example.com$request_uri;
}
Run Code Online (Sandbox Code Playgroud)


小智 -1

在 Nginx 配置文件中,添加以下服务器块。

server {
listen 80 default;
rewrite ^ http://your_domain_name.com$request_uri permanent;
}
Run Code Online (Sandbox Code Playgroud)