I was using this as a source of information to draw on: https://www.nginx.com/blog/deploying-nginx-plus-as-an-api-gateway-part-2-protecting-backend-services/#access-control
My server is running a docker container behind nginx. This container's majority API endpoints need to remain available to anyone(though I may look at rate-limiting those at a later date), but two end points need to be restricted. My current config, which seems to be working as intended, looks like this:
server {
listen 80;
server_name sub.domain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name sub.domain.com;
ssl_certificate /etc/letsencrypt/live/sub.domain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/sub.domain.com/privkey.pem;
location / {
location = /api_endpoint {
if ($remote_addr != xxx.xxx.xxx.xxx) {
return 403; # Forbidden
}
proxy_pass http://localhost:8000;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
}
location = /another/api_endpoint {
if ($remote_addr != xxx.xxx.xxx.xxx) {
return 403; # Forbidden
}
proxy_pass http://localhost:8000;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
}
proxy_pass http://localhost:8000;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
}
}
I don't like copy pasting code without knowing what exactly what's happening. Each chuck of:
proxy_pass http://localhost:8000;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
Was copied from a different set of docs, unrelated to this docker container. Because those docs laid out a working config for that project I just trusted it, but now that I'm adapting it I'm a little more curious and reading through this page for an explanation. But if anyone has feedback on trimming those blocks I'm all ears.
What my main question is about, and what I'd really like to know, is if this method is okay or if there are better methods to achieve the same goal of gating API endpoints to specific hosts making those requests?
With 2 other secondary questions to that primary one:
- Where I have
xxx.xxx.xxx.xxx
I first attemptedxxx.domain.com
without luck. Does nginx not resolve DNS names for this purpose? - For my use case gating these 2 endpoints to a single remote host is just fine, but I could see situations where allowing multiple hosts would be useful. Something like this is the closest I could find to maybe doing this, but again am all ears for alternatives.
Thank you very much for reading!