Ollama访问限制

发布于:

Ollama访问限制 | Eucalyptushttps://blog.mingliangstar.com/2026/05/21/Ollama%E8%AE%BF%E9%97%AE%E9%99%90%E5%88%B6/

Nginx+Basic Auth认证

生成密码文件

复制代码
# 安装工具
yum install httpd-tools -y

# 创建密码文件(用户名 admin)
htpasswd -c /www/server/pass/ollama.pass admin

# 输入密码,比如 MySecurePass123

修改nginx配置文件

在之前配置ollama的反向代理的nginx配置文件中设置Basic Auth认证实现访问限制

复制代码
    #BASICAUTH START
    auth_basic "Ollama API Auth";
    auth_basic_user_file /www/server/pass/ollama.pass;
    #BASICAUTH END

重启nginx

复制代码
nginx -t
systemctl reload nginx

测试

复制代码
# 不带认证 → 401 Unauthorized
curl https://ollama.mingliangstar.com/api/tags

# 带认证 → 成功
curl https://admin:MySecurePass123@ollama.mingliangstar.com/api/tags

后端Node.js代理

但是这样的话再前端调用的时候需要把账号和密码写到前端js中,还是有泄露的风险,这时我们可以使用后端代理。前端 JS 直接调用后端代理,后端代理内部带 Basic Auth 访问 Ollama。

架构图

复制代码
用户浏览器 → Hexo 博客页面 → JS 调用 https://ollama.mingliangstar.com
                                              ↓
                                    ECS Nginx (无认证,或简单限流)
                                              ↓
                                    Node.js 代理 (localhost:3001)
                                              ↓
                                    带 Basic Auth 调 Ollama (127.0.0.1:11434)
                                              ↓
                                    frps → frp隧道 → 本地虚拟机 Ollama

部署步骤

ces安装node.js
复制代码
# CentOS 7
curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -
yum install -y nodejs

# 验证
node -v
npm -v
创建代理服务
复制代码
mkdir -p /opt/ollama-proxy
cd /opt/ollama-proxy
npm init -y
npm install express node-fetch@2
创建proxy.js

记得配置CORS,不然会出现跨域访问问题

复制代码
const express = require('express');
const fetch = require('node-fetch');

const app = express();

// ========== CORS 中间件 ==========
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'https://blog.mingliangstar.com');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    
    if (req.method === 'OPTIONS') {
        return res.sendStatus(204);
    }
    next();
});
// =================================

app.use(express.json({ limit: '10mb' }));

// Ollama 配置
const OLLAMA_HOST = 'http://127.0.0.1:11434';
const AUTH_USER = 'admin';
const AUTH_PASS = 'MySecurePass123';

// 生成 Basic Auth 头
const basicAuth = 'Basic ' + Buffer.from(`${AUTH_USER}:${AUTH_PASS}`).toString('base64');

// 健康检查
app.get('/health', (req, res) => {
    res.json({ status: 'ok' });
});

// 代理 /api/generate
app.post('/api/generate', async (req, res) => {
    try {
        const response = await fetch(`${OLLAMA_HOST}/api/generate`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': basicAuth
            },
            body: JSON.stringify(req.body),
            timeout: 60000
        });

        if (!response.ok) {
            const text = await response.text();
            return res.status(response.status).json({ error: text });
        }

        const data = await response.json();
        res.json(data);

    } catch (err) {
        console.error('Proxy error:', err);
        res.status(500).json({ error: err.message });
    }
});

// 代理 /api/tags
app.get('/api/tags', async (req, res) => {
    try {
        const response = await fetch(`${OLLAMA_HOST}/api/tags`, {
            headers: { 'Authorization': basicAuth }
        });
        const data = await response.json();
        res.json(data);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

const PORT = 3001;
app.listen(PORT, '127.0.0.1', () => {
    console.log(`Ollama proxy running on http://127.0.0.1:${PORT}`);
});
用PM2守护进程
复制代码
npm install -g pm2

# 启动
pm2 start proxy.js --name ollama-proxy

# 开机自启
pm2 startup
pm2 save

# 查看状态
pm2 status
pm2 logs ollama-proxy
修改ollama反向代理nginx的配置文件
复制代码
    #PROXY-CONF-START
    location ^~ / {
      proxy_pass http://127.0.0.1:3001;   # 改成代理端口
      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Real-Port $remote_port;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Forwarded-Host $host;
      proxy_set_header X-Forwarded-Port $server_port;
      proxy_set_header REMOTE-HOST $remote_addr;
      
      proxy_connect_timeout 60s;
      proxy_send_timeout 600s;
      proxy_read_timeout 600s;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection $connection_upgrade;
    }
    #PROXY-CONF-END
重启nginx
复制代码
nginx -t
systemctl reload nginx
测试验证
复制代码
# 测试代理健康
curl http://127.0.0.1:3001/health

# 测试生成
curl -X POST http://127.0.0.1:3001/api/generate \
  -H "Content-Type: application/json" \
  -d '{"model":"qwen2.5:0.5b","prompt":"你好","stream":false}'
相关推荐
妙妙屋(zy)4 小时前
Claude Code+CC-Switch+CC-Connect+飞书使用教程
ai
小七-七牛开发者7 小时前
Coding Agent 规则管理:CLAUDE.md、Skills、Hooks、Subagents 到底怎么选?
ai·大模型·agent·claude·token·loop·mcp·claudecode·ai coding
doiito13 小时前
左脚踩右脚:让 LLM 自进化的 Agent 轨迹训练法——为什么它能补上主流范式的最后一块拼图
ai·系统设计
带刺的坐椅1 天前
从 Claude Code 隐私争议,看 SolonCode 的设计选择
ai·llm·agent·claudecode·soloncode·codingplan
lincats1 天前
Claude Code项目越写越乱?这套清理流程能救你
ai·ai agent·claude code
云燕实验室CloudLab1 天前
《AI开始"抱团"思考了!多智能体 + 思维图到底有多强?》
ai·学习工具·智慧学伴
小七-七牛开发者1 天前
论文解读:DeepSeek DSpark 在真实高并发推理服务中,如何保证 Token 生成又好又快?
ai·大模型·编程·ai coding
doiito2 天前
【Agent Harness】Gliding Horse 核心设计理念,不跟风开发自己的AI Agent
ai·rust·架构设计·系统设计·ai agent
doiito3 天前
【Agent Harness】Gliding Horse 的 L2 作战地图:让多 Agent 协作从“摸黑”变成“透明”
ai·rust·架构设计·系统设计·ai agent
xiezhr3 天前
逛GitHub发现一款免费带有AI功能的数据库管理工具DBX
ai·开源软件·自然语言·数据库管理工具