Search code examples
amazon-web-servicesnginxamazon-ec2amazon-route53elastic-ip

In AWS I need help for deny url by public ip or public dns and to allow only access by domain (CNAME)


I have aws ec2 with elastic ip and route53 with my domain and have nginx in server, this works fine but,

i have seen how other websites work, amazon.com udemy.com. If you access directly by public ip or public dns you throw an error. My question is how can I configure it to do the same.

example:
browser url by domain: amazon.com = ok
browser url by public ip: 52.222.137.64 = 400-403 error.
browser url by public dns: server-52-222-137-64.ams50.r.cloudfront.net = 400-403 error.

browser url by domain: example.com = ok
browser url by public ip: 124.34.32.245 = ok.
browser url by public dns: ec2-124.34.32.245.eu-west-3.compute.amazonaws.com = ok.

Thanks all for your help.

example is substitute for my domain, this is my config.

server {
    listen                  8089 ssl http2;
    listen                  [::]:8089 ssl http2;
    server_name             example.com;
    root                    /var/www/example.com/public;

    # SSL
    ssl_certificate         /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key     /etc/letsencrypt/live/example.com/privkey.pem;
    #ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
    ssl_dhparam             /etc/letsencrypt/ssl-dhparams.pem;

    # security
    include                 nginxconfig.io/security.conf;

    location / {
       proxy_set_header Accept-Encoding "";
        try_files $uri $uri/ /index.html;
    }

    # additional config
    include                 nginxconfig.io/general.conf;


}

server {
    listen      8080;
    listen      [::]:8080;
    server_name example.com;
    include     nginxconfig.io/letsencrypt.conf;

    location / {
       return 301 https://example.com$request_uri;
    }
}

I forgot to mention that I also use docker, I don't know if that will have something to do with it


Solution

  • Correct way to solve this problem in "AWS world" would be to use Application Load balancer with listener rules in front of your EC2 instance and place your actual server in Auto Scaling Group.

    This provides a lot of other benefits:

    • AWS SLA does not work if your workload is not able to load balance between at least 2 availability zone
    • it is simple to add AWS generator TLS certificate (extra bonus: it will auto re-new)
    • build in certain amount of DDoS protection
    • auto scaling
    • instance refresh
    • failover

    please note that in order for apex domain name to work, it would be best to migrate the actual domain to AWS Route53, or at least delegate controls to AWS.