Skip to content

绑定反向代理

🌐 Bind a reverse proxy

假设你想在反向代理后运行 Hono 应用。在这种情况下,你可能需要反映 x-forwarded-proto 头的值。例如,你需要能够获取 c.req.urlx-forwarded-proto 指定的 URL 的协议。

🌐 Suppose you want to run the Hono application behind a reverse proxy. In that case, you may need to reflect the value of the x-forwarded-proto header. For example, you need to be able to get the protocol of the URL specified by x-forwarded-proto in c.req.url.

处理这个的最佳做法是在 Hono 的 app.fetch 之前创建一个新的 Request 对象,并将其传递给 app.fetch

🌐 The best practice for handling this is to create a new Request object before Hono's app.fetch and pass it to 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))
  },
})

Hono 中文网 - 粤ICP备13048890号