Skip to content

IP 限制中间件

¥IP Restriction Middleware

IP 限制中间件是根据用户的 IP 地址限制对资源的访问的中间件。

¥IP Restriction Middleware is middleware that limits access to resources based on the IP address of the user.

导入

¥Import

ts
import { Hono } from 'hono'
import { ipRestriction } from 'hono/ip-restriction'

用法

¥Usage

对于在 Bun 上运行的应用,如果你只想允许从本地访问,可以按如下方式编写。指定你想要在 denyList 中拒绝的规则和你想要在 allowList 中允许的规则。

¥For your application running on Bun, if you want to allow access only from local, you can write it as follows. Specify the rules you want to deny in the denyList and the rules you want to allow in the allowList.

ts
import { Hono } from 'hono'
import { getConnInfo } from 'hono/bun'
import { ipRestriction } from 'hono/ip-restriction'

const app = new Hono()

app.use(
  '*',
  ipRestriction(getConnInfo, {
    denyList: [],
    allowList: ['127.0.0.1', '::1'],
  })
)

app.get('/', (c) => c.text('Hello Hono!'))

将适合你环境的 ConnInfo 助手 中的 getConninfo 作为 ipRestriction 的第一个参数传递。例如,对于 Deno,它看起来像这样:

¥Pass the getConninfo from the ConnInfo helper appropriate for your environment as the first argument of ipRestriction. For example, for Deno, it would look like this:

ts
import { getConnInfo } from 'hono/deno'
import { ipRestriction } from 'hono/ip-restriction'

//...

app.use(
  '*',
  ipRestriction(getConnInfo, {
    // ...
  })
)

规则

¥Rules

按照以下说明编写规则。

¥Follow the instructions below for writing rules.

IPv4

  • 192.168.2.0 - 静态 IP 地址

    ¥192.168.2.0 - Static IP Address

  • 192.168.2.0/24 - CIDR 表示法

    ¥192.168.2.0/24 - CIDR Notation

  • * - 所有地址

    ¥* - ALL Addresses

IPv6

  • ::1 - 静态 IP 地址

    ¥::1 - Static IP Address

  • ::1/10 - CIDR 表示法

    ¥::1/10 - CIDR Notation

  • * - 所有地址

    ¥* - ALL Addresses

错误处理

¥Error handling

要自定义错误,请在第三个参数中返回 Response

¥To customize the error, return a Response in the third argument.

ts
app.use(
  '*',
  ipRestriction(
    getConnInfo,
    {
      denyList: ['192.168.2.0/24'],
    },
    async (remote, c) => {
      return c.text(`Blocking access from ${remote.addr}`, 403)
    }
  )
)

Hono v4.7 中文网 - 粤ICP备13048890号