为 ollama 服务增加 apikey 进行访问控制保护
问题描述:
在需要暴露本地 ollama 的服务API 能力到公网,但ollama本身没有提供通用的 apikey 功能,如果任何人都可以访问,一旦被网络爬虫爬取,滥用算力的风险太大。网上有很教程使用nginx 的 ngx_http_keyauth_module,需要重新编译安装的步骤过多。对于个人或小团队使用,一个 apikey 足够了, 所以可以考虑将 apikey 写入 nginx 配置文件中,然后使用判断请求协议头的方法来进行判断。
实现方案:
创建 /etc/nginx/sites-enabled/ollama 文件,文件内容如下:
server {
listen 9180;
server_name www.domain.com domain.com;
location / {
if ($http_Authorization != "Bearer your-api-key") {
return 403 'Api Key incorrect.';
}
proxy_pass http://127.0.0.1:11434/;
}
}
其中 your-api-key 替换为你想设置的apikey 字符串。
然后执行 sudo systemctl restart nginx 重启 nginx 服务。使用如下命令进行测试:
% curl -H "Authorization: Bearer your-api-key" http://localhost:11434/
Ollama is running.
% curl http://localhost:11434/
Api Key incorrect.