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

我希望我的服务器的IP被重写为一个域名的URL,但我最难的时候弄清楚如何做到这一点。

例如,当我在浏览器中input213.34.54.xxx时,我希望它被重写为mydomain.com,而不是显示IP地址。

我目前的configuration如下:

/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; } 

在/ 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; } 

我已经尝试添加到mydomainconfiguration文件中的服务器指令:

 rewrite ^ $scheme://mydomain.com$request_uri redirect; 

但是我的浏览器中出现了太多的REDIRECTS错误。

至less,我可以通过在服务器指令中使用这个来防止显示IP地址:

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

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

任何我可能做错的见解将非常感激!

谢谢!

其实上面的答案不起作用(至少对我来说)。 我想这个问题已经提出了提问者找到了他的解决方案,但是因为我搜索了谷歌和很多链接到这里,也许这个解决方案将帮助其他人,只需将其添加到您的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; } 

将一个新的服务器实例添加到我的域名虚拟主机文件的底部,如下所示:

 server { listen xxx.xxx.xxx.xxx:80; server_name xxx.xxx.xxx.xxx; rewrite ^ http://example.com$request_uri? permanent; } 

/etc/init.d/nginx重新加载

注意:我添加这个重写的唯一原因是因为我的一个服务器的IP地址在Google搜索结果中结束,这可能会导致重复内容的问题。 如果这没有发生,我不会加重重写。 您可以通过搜索您的IP地址来查看您的服务器IP是否在搜索结果中:

网站:xxx.xxx.xxx.xxx

您需要为每个重写规则编写不同的服务器块

 # say this is your default BIG block server { listen 80 default_server; server_name example.com; passenger_enabled on; rails_env production; root /var/www/your_app/current/public/; } # forwarding to main block server { listen 80; server_name www.example.com; return 301 http://example.com$request_uri; } # forwarding to main block server { listen 80; server_name 55.55.55.55; return 301 http://example.com$request_uri; } 

也可以使用一个服务器块从许多IP重定向。

 server { listen 80; listen 443; server_name 172.20.0.2 172.20.0.3 172.20.0.4; return 301 $scheme://www.yourdomain.com$request_uri; } 

碰巧也有一个常规PCI合规性查找(泄漏私有IP),可以使用这个策略来解决。

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

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