香港云服务器上配置 Dify 访问 Gemini API
记录一下在香港云服务器上配置 Dify 访问 Gemini API 的过程
当时买的时候想着香港位置更近当代理使的,最近新创了个 google 账户正好有赠金,就打算部署个 Dify 玩玩,但香港 IP 直接访问 gemini API 会返回 400 user location not support 错误,于是在站内搜了下给 Dify 容器配置代理的教程: 【最新适配】Dify 海外模型代理配置(一次通关). 过程太复杂了懒得折腾,于是考虑直接修改 baseURL, 用手头另一个日本的服务器转发.
但直接在 nginx 中配置转发后发现还是 400 错误,我还以为没配成功,最后在日本服务器试了下发现可能因为是机房 IP, 直接访问也是 400, 只能考虑用 cloudflare WARP 出站.
我用的是 3x-ui, 出站规则里可以直接配置 WARP, 然后创建一个本地 http 入站,在路由规则里设置这个入站用 WARP 出站
最后让 AI 生成了个小脚本,得先把 nginx 的流程转到 flask 服务的端口,再用 flask 转给 3x-ui 上的代理,感觉也挺复杂,有没有佬知道更简便的方法
from flask import Flask, request, Response
import requests
app = Flask(__name__)
# 31699是3x-ui上配置的本地代理端口
PROXIES = {
'http': 'http://127.0.0.1:31699',
'https': 'http://127.0.0.1:31699'
}
# Gemini 官方 API 域名
TARGET_URL = 'https://generativelanguage.googleapis.com' @app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE']) def proxy(path):
# 构造请求 URL
url = f"{TARGET_URL}/{path}" # 获取原始请求的查询参数
params = request.args
# 获取原始请求的 Header,并移除 Host 避免冲突
headers = {k: v for k, v in request.headers if k.lower() != 'host'}
try:
# 转发请求到 Google,并使用本地代理
resp = requests.request(
method=request.method,
url=url,
headers=headers,
data=request.get_data(),
params=params,
proxies=PROXIES,
stream=True, # 支持流式输出
timeout=300
)
# 构造响应给 Nginx
excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
headers = [(name, value) for (name, value) in resp.raw.headers.items()
if name.lower() not in excluded_headers]
return Response(resp.iter_content(chunk_size=1024), resp.status_code, headers)
except Exception as e:
return str(e), 500 if __name__ == '__main__':
app.run(host='127.0.0.1', port=5346)
