Restrict requests to localhost using nginx config file

I am fairly new to ngnix. I am trying to do something that I believe is fairly straight forward, but I have yet to figure out how to accomplish the task.

I have a subdomain named apis.mydomain.com that is a node application with a few routes that work fine and is on my Digital Ocean droplet. I have mysub.mydomain.com which is also on my Digital Ocean droplet. I want to only allow calls to apis.mydomain.com to come from mysub.mydomain.com. Based on everything I have read on the matter, I thought the following would work in the nginx config file for apis.mydomain.com, but it does not seem to work.

  location / {
    allow 127.0.0.1;
    deny all;
  }

This is not CORS related. I am wanting to prevent other servers from trying to use my API.

1 Like

Looks like it should work, maybe the config isn’t being loaded for whatever reason? I’ve had many config problems resolved when I realized I was editing the wrong file. I test this by throwing a syntax error into the file, reloading, and seeing if it dies.

I’d also recommend using listen 127.0.0.1:80 regardless.

@chuckadams Here is what I have in the config file.

server {
  server_name apis.mydomain.com;

  listen [::]:443 ssl; # managed by Certbot
  listen 443 ssl; # managed by Certbot
  ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

   location / {
    allow 127.0.0.1;
    deny all;
    proxy_pass http://localhost:3000;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    # Following is necessary for Websocket support
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
   }
}

server {
  if ($host = apis.mydomain.com) {
    return 301 https://$host$request_uri;
  } # managed by Certbot

  listen 80;
  listen [::]:80;

  server_name apis.mydomain.com;
  location / {
    return 301 https://apis.mydomain$request_uri;
  }
}

I am running a Node express application on port 3000 which services the api.