
本文示範如何用 Nginx 反向代理為 Elasticsearch 加上一層 HTTP 基本認證。這是最輕量的保護方式;若需要更完整的權限模型,則可採用 Elasticsearch 官方的 shield 外掛。
1. 確認 htpasswd 是否已存在
which htpasswd
有回傳路徑代表已安裝:

沒有的話依發行版安裝:
# Ubuntu
apt-get -y install apache2-utils
# CentOS
yum -y install httpd-tools
2. 產生密碼檔
htpasswd -c -d /etc/nginx/conf.d/pass_file nginxuser
執行後會提示輸入並確認密碼(此例假設為 pass123),於是帳號與密碼分別是 nginxuser 與 pass123。

可以看到 pass_file 已產生在 /etc/nginx/conf.d/ 目錄下。
1. 建立 nginx_http_auth_basic.conf
events {
worker_connections 1024;
}
http {
upstream elasticsearch {
server wb-elk:9200;
}
server {
listen 8080;
auth_basic "Protected Elasticsearch";
auth_basic_user_file /etc/nginx/conf.d/pass_file;
location / {
proxy_pass https://elasticsearch;
proxy_redirect off;
}
}
}
幾個重點:upstream 的 server 可寫成 127.0.0.1:9200,此處用主機名稱;listen 決定對外埠口;auth_basic_user_file 指向剛才產生的密碼檔。
2. 停掉原本的 Nginx 服務
service nginx stop
service nginx status
先確認服務確實處於停止狀態。
3. 以自訂設定啟動
nginx -p $PWD/nginx/ -c $PWD/nginx_http_auth_basic.conf
service nginx status
直接訪問時會跳出瀏覽器的認證視窗,輸入帳密後才能取得回應:



補充一點:預設的 Elasticsearch 沒有任何認證機制,只要埠口可達,任何人都能讀寫索引。因此即使加了 Nginx 認證,也建議同時把 9200 埠口限制在內部網路,不要直接暴露於公網。