在 URL 与配置中正确书写 IPv6 字面地址

说明浏览器、curl、hosts 文件与 Nginx 配置里 IPv6 地址加方括号的规则及常见写法错误。

本页目录

为什么必须加方括号#

URL 里用冒号分隔主机名与端口(host:port),而 IPv6 地址本身含多个冒号。RFC 3986 规定:URI 的主机部分若是 IPv6 字面量,必须用方括号包起来,端口写在右括号之后。

text
https://[2400:3200::1]/              正确
https://[2400:3200::1]:8443/         正确,自定义端口
http://2400:3200::1/                 错误,会被当作主机名 + 非法端口
http://[::1]:8080/                   正确,本机回环

浏览器地址栏可以直接输入带方括号的地址;在 shell 里执行 curl 时要加引号,否则 [ ] 会被当作通配符展开:

bash
curl -6 -I "https://[2400:3200::1]/"
curl -6 -v "http://[::1]:8080/health"

链路本地地址与 Zone ID#

访问 fe80::/10 链路本地地址必须指定出接口(scope / zone id)。在 URL 里百分号需要编码为 %25:

text
http://[fe80::1%25eth0]/
http://[fe80::1%2512]/        Windows 用接口索引

命令行工具通常接受未编码写法:

bash
ping -6 fe80::1%eth0
ssh fe80::abcd%eth0
curl -6 "http://[fe80::1%25eth0]/"     # URL 内仍需 %25

hosts 文件里不加方括号#

hosts 文件是「地址 + 主机名」的逐行映射,没有端口概念,因此 IPv6 地址直接写,不加方括号:

text
# /etc/hosts  或  C:\Windows\System32\drivers\etc\hosts
::1             localhost
2400:3200::1    dns.example.local
2001:db8::10    nas.local
常见误区是把 hosts 也写成 [2400:3200::1] dns.example.local,这种写法不会被解析,表现为「ping 不通主机名」。方括号只用于带端口/协议 scheme 的 URI 与监听配置。

Nginx 中的写法#

场景写法说明
监听所有 IPv6listen [::]:80;方括号 + 端口
指定地址监听listen [2400:3200::1]:443 ssl;加方括号
上游是字面 IPv6proxy_pass https://[2001:db8::1]:443;加方括号
DNS 解析器resolver 2400:3200::1;不加方括号
允许网段allow 2001:db8::/32;CIDR,不加方括号
nginx
server {
    listen 80;
    listen [::]:80;
    server_name example.local;

    location / {
        proxy_pass http://[2001:db8::10]:8080;
        proxy_set_header Host $host;
    }
}

速查#

位置是否加方括号示例
URL / 浏览器地址栏是https://[::1]/
curl 参数(引号内)是"http://[::1]:8080/"
ping / ssh 目标否ping -6 fe80::1%eth0
hosts 文件否::1 localhost
Nginx listen / proxy_pass是listen [::]:443;
Nginx resolver / allow否resolver 2400:3200::1;