跳转到正文

接入反向代理 ​

假设你希望在反向代理后运行 Hono 应用,那么可能需要让应用反映 x-forwarded-proto 请求头的值。例如,你需要能够通过 c.req.url 获取由 x-forwarded-proto 指定的 URL 协议。

推荐的处理方式是在调用 Hono 的 app.fetch 之前创建一个新的 Request 对象,并将其传给 app.fetch。

Cloudflare Workers / Deno / Bun ​

ts
import { Hono } from 'hono'

const app = new Hono()

//...

export default {
  fetch: (req: Request) => {
    const url = new URL(req.url)
    url.protocol =
      req.headers.get('x-forwarded-proto') ?? url.protocol
    return app.fetch(new Request(url, req))
  },
}

Node.js ​

ts
import { Hono } from 'hono'
import { serve } from '@hono/node-server'

const app = new Hono()

serve({
  fetch: (req) => {
    const url = new URL(req.url)
    url.protocol =
      req.headers.get('x-forwarded-proto') ?? url.protocol
    return app.fetch(new Request(url, req))
  },
})

基于 MIT 许可证发布。