背景

自宅で動かしている Ollama + GenAI モデル(例えば phi4:14b)を、インターネット越しに使いたくなった。OpenVPN で穴を開けた上で、Nginx を使って自宅マシンへのプロキシを構成。

[ インターネット ]
       ↓
  VPSのnginx (443)
       ↓
OpenVPN経由のプライベートIP (100.64.x.x)
       ↓
 自宅のGenAIサーバ (Ollama)

確かに便利ではあるが、「誰でも使える状態」にしてしまうのは少し怖くなった。 なので、Basic認証 を導入して、ユーザーとパスワードを知らないとアクセスできないようにした。

Nginx に Basic認証を追加する手順

  1. 認証用パスワードファイルを作成する まず、htpasswd コマンドを使って .htpasswd を作成。
sudo apt install apache2-utils  # 初回のみ

sudo htpasswd -c /etc/nginx/.ollama_htpasswd user1

2. Nginx の設定に認証を追加

/etc/nginx/nginx.conf

server {
    listen 443 ssl;
    server_name hoge.ingenboy.com;

    ssl_certificate /etc/letsencrypt/live/ollama.ingenboy.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/ollama.ingenboy.com/privkey.pem;

    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept';

    location / {
        # Basic 認証を有効にする
        auth_basic "Restricted Area";
        auth_basic_user_file /etc/nginx/.ollama_htpasswd;

        proxy_pass http://100.64.1.41:11434;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

3. 反映

sudo nginx -t && sudo systemctl reload nginx

4. 確認

curl -v https://hoge.ingenboy.com

→ 401 Unauthorized

curl -u user1:yourpassword https://hoge.ingenboy.com