Nginx: How to allow only localhost (or specific IPs) to POST to controller endpoints?


I have a couple of login controllers that receive only POST requests on urls, for example:

My current Nginx configuration for is set up like this:

upstream app {
  server max_fails=5 fail_timeout=60s;
server {

  listen [::]:443 ssl; # managed by Certbot
  listen 443 ssl; # managed by Certbot

  location / {
    proxy_http_version 1.1;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-Cluster-Client-Ip $remote_addr;

    # The Important Websocket Bits!
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    proxy_pass http://app;

My router.ex is set up like the following:

scope "/ex", ExchatWeb do
    pipe_through :api

    post "/users/login", UserController, :login
    post "/users/anon-login", UserController, :anon_login

Basically, I would only like the local host (or specified IP addresses) to be able to post to those endpoints in the router. How can I set this up in Nginx?

I’ve tried adding the following to the Nginx server blocks (and other variations + before/after root location block, etc), but it’s not working. The Nginx server location configs are always a bit tricky for me, I’m sure there is a simple solution.

location = /ex/user/login { #attempt to restrict endpoint to localhost only
    deny all;


location ^~ /ex/user/ { # attempt to restrict entire /ex/user endpoint folder to localhost only
    deny all;


1 Like