diff --git a/server/src/routes/sub.ts b/server/src/routes/sub.ts index ecc3ce9..8f2d11a 100644 --- a/server/src/routes/sub.ts +++ b/server/src/routes/sub.ts @@ -34,9 +34,18 @@ function touchToken(id: string, count: number) { .run(); } -/** 订阅 URL 基址:直接取本次请求的 origin——客户端能请求到这里,origin 就一定可达 */ -function baseUrl(c: { req: { url: string } }): string { - return new URL(c.req.url).origin; +/** + * 订阅 URL 基址:取本次请求的 origin——客户端能请求到这里,origin 就一定可达。 + * 部署在 nginx 等反代之后时,Node 只看到明文 http 与内网 Host,需读 X-Forwarded-Proto/Host 还原外部地址, + * 否则 Surge 的 #!MANAGED-CONFIG 与 Clash 的 provider URL 会指向不可达的 http://127.0.0.1。 + */ +function baseUrl(c: { req: { url: string; header: (name: string) => string | undefined } }): string { + const url = new URL(c.req.url); + const proto = c.req.header('x-forwarded-proto')?.split(',')[0].trim(); + const host = c.req.header('x-forwarded-host')?.split(',')[0].trim(); + if (proto) url.protocol = `${proto}:`; + if (host) url.host = host; + return url.origin; } export const subRoute = new Hono()