Search code examples
nginxwebserver.htpasswd

Http basic auth with nginx on different port


I've got a website with a reverse front-end proxy in which my app listens on port 3000. I've got another app that sits on 3001 which is part of the same directory that serves the contents for the site on port 3000.

What I want to do.

Anyone going to mydomain.com:3001 would be prompted for auth_basic credentials. Anyone going to mydomain.com would get through normally.

My current nginx config:

upstream app_example {
      server 127.0.0.1:3000;
      keepalive 64;
}

server {
      root /var/www/example;
      listen 0.0.0.0:80;
      server_name example.com example;
      access_log /var/log/nginx/app_example.log;
}

Would it be something like this?

upstream app_tools {
    server 127.0.0.1:3001;
}

server {
        listen 80;
        server_name example.com example;

        location / {
        auth_basic      "secured site tools";
        auth_basic_user_file /var/www/example/.htpasswd;
            proxy_pass http://app_tools;
        }
}

Solution

  • You need to create different server for mydomain.com:3001 and mydomain.com

    upstream app_tools {
          server 127.0.0.1:3000;
          keepalive 64;
    }
    
    
    server {
          root /var/www/example;
          listen 0.0.0.0:80;
          server_name mydomain.com;
          access_log /var/log/nginx/app_example.log;
          location / {
                proxy_pass http://app_tools;
          }  
    }
    
    
    server {
          root /var/www/example;
          listen 0.0.0.0:3001;
          server_name mydomain.com;
          access_log /var/log/nginx/app_example_secure.log;
          location / {
                auth_basic      "secured site tools";
                auth_basic_user_file /var/www/example/.htpasswd;
                proxy_pass http://app_tools;
          }  
    }
    

    But remember what security through obscurity - bad idea.