Secure Loki Access with NGINX Authentication

Learn how to protect Loki with NGINX using HTTP Basic Authentication, ensuring only authorized users can access logs. This guide covers password protection, configuration, and testing.

Banner

By default, Loki has no authentication mechanism. Exposing it to the internet without protection can be a security risk. In this guide, we’ll set up NGINX HTTP Basic Authentication to restrict access with a username and password.

1. Install Nginx (if not installed):


sudo apt update && sudo apt install nginx -y

2. Configure Nginx change the config file **/etc/nginx/nginx.conf ** to the following:


events {
worker_connections 1024;

}
http {

server {
        listen 80;

        server_name YOUR SERVER IP;
        client_max_body_size 10000M;
        
        
        # loki
        location /loki/ {
		auth_basic "Restricted Access";
    		auth_basic_user_file /etc/nginx/.loki_auth;

		proxy_pass http://localhost:3100/loki/;
		proxy_set_header Host $host;
		proxy_set_header X-Real-IP $remote_addr;
        	}
        }
}

3: Install Apache Utils for htpasswd

To create a password file, install apache2-utils (includes htpasswd command):


sudo apt update
 sudo apt install apache2-utils -y

4: Create a Password File

Run the following command to create a new user and set a password:


sudo htpasswd -c /etc/nginx/.loki_auth YOUR_USERNAME

Replace YOUR_USERNAME with your desired username. You'll be prompted to enter a secure password.

To add more users later, use:


sudo htpasswd /etc/nginx/.loki_auth YOUR_USER

**5: Verify and Restart NGINX **

Check for syntax errors:


sudo nginx -t

If everything is fine, restart NGINX:


sudo systemctl restart nginx

**6: Test Loki Access **

fetch latest 6 hour logs


curl -u YOUR_USERNAME:YOUR_PASSWORD -G -s "http://YOUR SERVER IP/loki/api/v1/query_range"   --data-urlencode 'query={job="database_backup_log"}'   --data-urlencode 'limit=10'   --data-urlencode "start=$(date -u -d '6 hours ago' +%s%N)"

Conclusion

Your Loki instance is now protected with username & password authentication via NGINX. This method adds an essential security layer, preventing unauthorized access.

For even stronger security, consider enabling HTTPS with Let's Encrypt. 🚀

Secure Loki Access with NGINX Authentication | Software Engineer Blog