How to use auth proxy with nginx?

For what it’s worth, thought I’d share here (and a couple of other places… cause it took me a while to crack…) how I linked my grafana to nginx authproxy using basic authentication:

NGINX.CONF: (you have to create the password file beforehand)

worker_processes 1;
daemon off;
error_log <%= ENV["APP_ROOT"] %>/logs/error.log;
events { worker_connections 1024; }

http {
  log_format cloudfoundry '$http_x_forwarded_for - $http_referer - [$time_local] "$request" $status $body_bytes_sent';
  access_log <%= ENV["APP_ROOT"] %>/nginx/logs/access.log cloudfoundry;
  default_type application/octet-stream;
  include mime.types;
  sendfile on;
  gzip on;
  tcp_nopush on;
  keepalive_timeout 30;

  server {
    listen <%= ENV["PORT"] %>;
    server_name localhost;

    # The internal IP of the VM that hosts the grafana
    set $upstream <%= ENV["GRAFANA_HOST"] %>:<%= ENV["GRAFANA_PORT"] %>;
    auth_basic "Users Area";
    auth_basic_user_file .htpasswd; 

    location ~ /\.ht { deny  all; }

    location ~ ^/grafana/(.*) {
      proxy_pass http://$upstream/$1;
      proxy_set_header X-WEBAUTH-USER $remote_user;
      proxy_set_header Authorization "";
    }

    location / {
      root <%= ENV["APP_ROOT"] %>/release;
      index index.html index.htm Default.htm;
      try_files $uri $uri/ =404;
    }
  }
}

And the minimal grafana.ini setup:

[server]
http_port = 3001
domain = localhost
root_url = http://grafana.staged-by-discourse.com/grafana/
[users]
allow_sign_up = false
[auth.proxy]
enabled = true
1 Like