多文件配置

优质
小牛编辑
126浏览
2023-12-01

多文件配置

自版本4.23.0起,v2ray程序支持使用多个配置文件。

多配置文件的主要作用在于分散不同作用模块配置,便于管理和维护。该功能主要考虑是为了丰富v2ray生态链,比如对于GUI的客户端,一般只实现节点选择等固定的功能,对于太复杂的配置难以图形化实现;只需留一个confdir的自定义配置目录供配置复杂的功能;对于服务器的部署脚本,只需往confdir添加文件即可实现配置多种协议...等等。

多文件启动信息例子

启动信息中会提示依次读入的每个配置文件,留意启动信息是否符合你预设的顺序。

$ v2ray -c v2ray.json -c 00_base.json -c 01_info.json -c 02_log.json -c outbound.json
V2Ray v4.23.0-version (user) 20200311-000000 (go1.13.8 linux/mipsle)
A unified platform for anti-censorship.
2020/03/22 18:40:00 [Info] v2ray.com/core/common/platform/ctlcmd: <v2ctl message>
v2ctl> Read config:  00_base.json
v2ctl> Read config:  01_info.json
v2ctl> Read config:  02_log.json
v2ctl> Read config:  outbound.json
v2ctl> [ outbound.json ] updated outbound with tag:  proxy

用法说明

命令行的-config可以多次指定。(也可以简写为-c,完全等效。)

./v2ray -config base.json -config cf1.json -c cf2.json -c cf3.json

或者用-confdir参数指定一个目录,程序会按文件名顺序读取目录内的.json文件。

./v2ray -confdir /etc/v2ray/confs

也可组合使用。(注意,目录内的配置级别作用在-config参数后,不管-confdir参数的位置)

./v2ray -c cf1.json -c cf2.json -confdir /etc/v2ray/confs

也可使用环境变量v2ray.location.confdirV2RAY_LOCATION_CONFDIR指定confdir。参数-confdir的作用优先于环境变量,如果参数指定了有效的目录则不再读取环境变量中的路径。

规则说明

普通对象({}

在json的顶级对象当中,后者覆盖或补充前者。

比如:

  • base.json

    {
      "log": {},
      "api": {},
      "dns": {},
      "stats": {},
      "policy": {},
      "transport": {},
      "routing": {},
      "inbounds": []
    }
    
  • outbounds.json

    {
      "outbounds": []
    }
    

以多配置启动v2ray: ./v2ray -c base.json -c outbounds.json,这两个配置文件的就等效于合成一起的整配置。当需要修改出口节点,只需要修改outbounds.json内容。

如果需要改编日志log的级别,也不需要改base.json,后续加一个配置:

  • debuglog.json
    {
      "log":{"loglevel": "debug"}
    }
    

启动时放置在base后,即可输出debug级别的日志:

./v2ray -c base.json -c outbounds.json -c debuglog.json

数组([]

在json配置中的inboundsoutbounds是数组结构,他们有特殊的规则:

  • 当配置中的数组元素有2或以上,覆盖前者的inbounds/oubounds;
  • 当配置中的数组元素只有1个时,查找原有tag相同的元素进行覆盖;若无法找到:
    • 对于inbounds,添加至最后(inbounds内元素顺序无关)
    • 对于outbounds,添加至最前(outbounds默认首选出口);但如果文件名含有tail(大小写均可),添加至最后。

借助多配置,可以很方便为原有的配置添加不同协议的inbound,而不必修改原有配置。

以下例子不是有效配置,只为展示上述规则。

  • 000.json

    {
      "inbounds": [
        {
          "protocol": "socks",
          "tag":"socks",
          "port": 1234
        }
      ]
    }
    
  • 001.json

    {
      "inbounds": [
        {
          "protocol": "http",
          "tag":"http"
        }
      ]
    }
    
  • 002.json

    {
      "inbounds": [
        {
          "protocol": "socks",
          "tag":"socks",
          "port": 4321
        }
      ]
    }
    

三个配置将会合成为:

{
    "inbounds": [
      {
        "protocol": "socks",
        "tag":"socks",
        "port": 4321 // <--- 002顺序在000后,因此覆盖tag为socks的inbound端口为4321
      },
      {
        "protocol": "http",
        "tag":"http"
      }
    ]
}