问题
I have a Rails app running on an AWS OpsWorks Nginx/Unicorn Rails Layer. I want my app to only process requests to api.mydomain.com and have my web server directly return a 404 if any request is made using the server's IP address.
I've implemented a custom cookbook that overrides unicorn/templates/default/nginx_unicorn_web_app.erb (from the opsworks-cookbooks repo: https://github.com/aws/opsworks-cookbooks). I copied the template file that exists in this repository and added a new server block at the top of the template:
server {
listen 80;
server_name <%= @instance[:ip] %>;
return 404;
}
I stopped and started my server to ensure that the customized template file gets used, but when I issue a request using the server's IP address it still gets routed to my Rails app.
Is this <%= @instance[:ip] %> not correct? Is there a way to log from within this template file so that I can more easily debug what is going wrong? I tried using Chef::Log.info, but my message didn't seem to get logged.
Thanks!
Edit: For anyone else having this issue... The answer below about setting up a default server block fixed one of my issues. My other issue was related to the fact that my cookbook updates were not even making their way to my instance and needed to manually refresh the cookbook cache: http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-installingcustom-enable-update.html
回答1:
EC2 instances have a private (typically RFC-1918) IP address. The Internet Gateway translates traffic to that address from the public address. If that private address is the address <%= @instance[:ip] %>
returns, then obviously, this configuration isn't going to do what you want.
Even if not, this isn't the correct approach.
Instead, you should define the default behavior of Nginx -- which is the first server
block -- to throw the error, and later in the config, declare a server block with the api DNS hostname and the behavior you want for normal operation.
See Why is nginx responding to any domain name?.
回答2:
Try adding a location block around the return statement "location /" refers to root
server {
listen 80;
server_name <%= @instance[:ip] %>;
location / {
return 404;
}
}
来源:https://stackoverflow.com/questions/32772341/disable-web-access-via-direct-ip-address-on-aws-opsworks-nginx-unicorn-server