user3332404
user3332404

Reputation: 171

Same server_name but different port number along with different user on Nginx?

I need to achieve something like, when user hit Domain IP/Keepalived Ip like z.z.z.z , basic http authentication should ask username and password. Now if user name is vikas it should redirect to z.z.z.z:5601 and if the user is gopal it should redirect to z.z.z.z:5602.

So here I have one major dependency on user , like I need to check before redirection if the user is Vikas or Gopal . I am trying following but it only works fine if I use single Location stenza .

upstream kibana {
        server 171.x.x.x:5601;
        server 172.x.x.x:5601;
        }
upstream kibana2 {
        server 171.x.x.x:5602;
        server 172.x.x.x:5602;
        }
        server {
        listen 80;
        listen 443 ssl;
        server_name z.z.z.z;
        location / {
        auth_basic      "protect kibana";
        auth_basic_user_file /etc/nginx/htpasswd.user;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://kibana;
                }
        location / {
        auth_basic      "protect kibana";
        auth_basic_user_file /etc/nginx/htpasswdkibana2.user;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://kibana2;
                }
        }

So in the second location directive I am using different http password file . So now the situation is , web page is asking user name and password but it does not pick any of them , I entered the credentials , it clears it and again asking for credentials . Can someone please help me to achieve this .

Regards Vikas

Upvotes: 1

Views: 1477

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146630

I think you can do that by inspecting the name of the user and send them to a backend based on that

map $remote_user $server_based_on_user {
   "vikas" "kibana";
   "gopal" "kibana2";
}

upstream kibana {

    server 171.x.x.x:5601;
    server 172.x.x.x:5601;
}

upstream kibana2 {

    server 171.x.x.x:5602;
    server 172.x.x.x:5602;
}

server {

    listen 80;
    listen 443 ssl;
    server_name z.z.z.z;

    location / {
        auth_basic "protect kibana";
        auth_basic_user_file /etc/nginx/htpasswd.user;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://$server_based_on_user$request_uri;
    }
}

The /etc/nginx/htpasswd.user file should have both the users defined

Upvotes: 1

Related Questions