V2Ray and XrayPublished

How to create a V2Ray subscription link

A V2Ray subscription link is an HTTPS URL that returns a user's share links, one per line, base64-encoded, plus a few response headers that clients read for traffic, expiry and refresh time. To create one without a panel, generate the list for each user, save it under a long random token, and serve it from nginx with no-store caching, a noindex header and the subscription-userinfo header. Then fetch it exactly as a client does before you give it to anyone.

ST Muntaha11 min read

A base64 subscription file fanning out into three server entries.
On this page
  1. Do you need to build your own subscription server?
  2. Which format should the link return?
  3. How do I generate the subscription file?
  4. How should I make per-user tokens?
  5. How do I serve a subscription over HTTPS with nginx?
  6. Which headers should a subscription send?
  7. How do I keep subscription links out of search engines?
  8. How do I rotate servers without breaking clients?
  9. How do I make a Shadowsocks subscription?
  10. How do I test a subscription link before I hand it out?

This guide is for operators. It covers how to build and serve the link: the format to return, the generator, the tokens, the nginx config, the headers, and how to test the result. To read a subscription instead, see How to decode a V2Ray subscription link. To watch one in production, see Monitoring V2Ray subscription URLs in production.

I tested the nginx config and the generator below on nginx 1.28.3 and Python 3.

Do you need to build your own subscription server?

Not if a panel already runs your servers. 3x-ui has a subscription server built in, on its own port (2096 by default), and Marzban serves one at /sub/<token>/. Both send the headers clients expect and can pick a format from the client's user agent. Configure those first. For problems with the 3x-ui one, see 3x-ui monitoring.

Build your own when you run plain Xray or sing-box servers without a panel, when one link has to combine servers from several panels, or when you want full control over names and order.

Return the base64 link list by default. It is the format almost every V2Ray-family client imports, and Mihomo can use it too, as a proxy provider. The other formats are complete client configs, which you have to template and keep in step with the list:

Format Content-Type Read by Notes
Base64 link list text/plain; charset=utf-8 v2rayN, v2rayNG, Hiddify, Streisand, Mihomo providers the default
Clash / Mihomo YAML text/yaml Mihomo and Clash Meta clients some desktop clients reject a profile with neither proxies nor proxy-providers
sing-box JSON application/json sing-box apps, as a remote profile a full config; the apps refresh it every 60 minutes by default
SIP008 JSON application/json; charset=utf-8, exactly Shadowsocks clients Shadowsocks servers only

Panels choose the format by user agent. I prefer one URL per format: it is easier to debug, and a client update that changes its user agent cannot switch a user to the wrong format.

For Mihomo users you do not need to translate every server into YAML. A short profile can point a provider at the user's own base64 URL, and Mihomo parses the list itself. I checked this profile with mihomo -t on Mihomo v1.19.33:

mixed-port: 7890
proxy-providers:
  main:
    type: http
    url: "https://sub.yourdomain.com/s/UhG0eSe6oBvbh-onp4ydKIctVxQnzOUo"
    interval: 3600
    health-check:
      enable: true
      url: https://www.gstatic.com/generate_204
      interval: 300
proxy-groups:
  - name: PROXY
    type: select
    use: [main]
rules:
  - MATCH,PROXY

The provider interval is in seconds. Details are in the Mihomo proxy-providers docs.

How do I generate the subscription file?

Write each user's links one per line, join them with a plain \n, encode the result as standard base64 with padding, and write it to a file named after the user's token. 3x-ui and Marzban both emit standard base64. v2rayN and v2rayNG also accept URL-safe base64 and missing padding, but many scripts and some clients do not, so give them nothing to fix.

The script below reads a users.json, writes one file per user, writes an nginx map with each user's usage header, and deletes the files of users who are no longer in the input. It writes every file to a temporary name and then renames it. A rename is atomic, so a client that fetches during a run gets the old list or the new one, never half of one. It also refuses to publish an empty list, because an empty list can wipe every server from the user's app on the next refresh.

#!/usr/bin/env python3
"""Build one base64 subscription file per user, plus the nginx map of usage headers."""
import base64, json, os, re, sys, tempfile

USERS = sys.argv[1] if len(sys.argv) > 1 else "/etc/subgen/users.json"
OUT_DIR = os.environ.get("SUB_DIR", "/var/www/sub/b64")
MAP_FILE = os.environ.get("SUB_MAP", "/etc/nginx/sub/userinfo.map")
TOKEN_RE = re.compile(r"^[A-Za-z0-9_-]{32}$")

def write_atomic(path, data):
    fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path))
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        f.write(data)
    os.chmod(tmp, 0o644)
    os.replace(tmp, path)  # readers see the old file or the new one, never half of one

def main():
    users = json.load(open(USERS, encoding="utf-8"))
    map_lines = []
    for u in users:
        if not TOKEN_RE.match(u["token"]):
            sys.exit(f"bad token for {u['name']}")
        links = [l.strip() for l in u["links"] if l.strip()]
        if not links:
            sys.exit(f"no links for {u['name']}, refusing to publish an empty list")
        body = base64.b64encode("\n".join(links).encode("utf-8")).decode("ascii")
        write_atomic(os.path.join(OUT_DIR, u["token"]), body)
        info = f'upload=0; download={u["used"]}; total={u["total"]}; expire={u["expire"]}'
        map_lines.append(f'"{u["token"]}" "{info}";')
    write_atomic(MAP_FILE, "\n".join(map_lines) + "\n")
    keep = {u["token"] for u in users}
    for name in os.listdir(OUT_DIR):
        if TOKEN_RE.match(name) and name not in keep:
            os.remove(os.path.join(OUT_DIR, name))  # a user removed from users.json stops working
    print(f"wrote {len(users)} subscriptions")

if __name__ == "__main__":
    main()

The input has one object per user. used and total are bytes, expire is Unix seconds, and 0 means no limit:

[
  {"name": "user-0412", "token": "UhG0eSe6oBvbh-onp4ydKIctVxQnzOUo",
   "used": 1073741824, "total": 53687091200, "expire": 1798761600,
   "links": [
     "vless://5f0c2a7e-3b1d-4e8a-9c6f-2d4b8a1e7c93@176.61.144.21:443?type=tcp&security=reality&sni=www.yourdomain.com&fp=chrome&pbk=Zx3qO8fJr2mK5vT1yN7cB4hW9pL6sD0aE2gU8iR5oQk&sid=6ba85179&flow=xtls-rprx-vision#nl-ams-1",
     "hysteria2://Hq8vN3sL@vpn.yourdomain.com:443/?sni=vpn.yourdomain.com#de-fra-1"
   ]}
]

Each user's links carry that user's own credential (the UUID or password), so never share one file between users. Percent-encode the names after #: a space is %20, and names in other scripts must be UTF-8 percent-encoded. Where used comes from is up to you: your billing system, or the traffic counters in Xray's stats API.

How should I make per-user tokens?

Make each token a long random string with no meaning, one per user. Python's secrets module gives 32 URL-safe characters from 24 random bytes:

python3 -c 'import secrets; print(secrets.token_urlsafe(24))'

The token is the only thing that protects the list, so treat it like a password:

  • Do not build it from a username, an email, an order number or a hash of any of them. Anything that can be guessed or enumerated will be.
  • Do not count on the host name being secret. Publicly trusted TLS certificates are published in Certificate Transparency logs, so sub.yourdomain.com is public the day you get its certificate.
  • To revoke a link, remove the user from users.json and run the generator: it deletes the file, so the URL returns 404 at once. To replace a leaked link, give the user a new token. There is no reason to keep the old one alive.

The SIP008 spec asks for the same thing in its own words: a delivery URL should carry a secret in its path or query, so it cannot be crawled.

How do I serve a subscription over HTTPS with nginx?

Serve the files as static content from a location that only matches a valid token shape, and add the headers there. Put this in /etc/nginx/conf.d/sub.conf. It needs nginx 1.25.1 or newer for the http2 on; line. On older versions, write listen 443 ssl http2; instead.

limit_req_zone $binary_remote_addr zone=sub:10m rate=30r/m;

map $sub_token $sub_userinfo {
    default "";
    include /etc/nginx/sub/userinfo.map;
}

server {
    listen 443 ssl;
    http2 on;
    server_name sub.yourdomain.com;

    ssl_certificate     /etc/letsencrypt/live/sub.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/sub.yourdomain.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;

    root /var/www/sub;
    server_tokens off;
    access_log off;            # every URL on this host is a credential
    limit_req_status 429;

    location ~ "^/s/(?<sub_token>[A-Za-z0-9_-]{32})$" {
        limit_req zone=sub burst=20 nodelay;
        default_type text/plain;
        charset utf-8;
        try_files /b64/$sub_token =404;

        add_header Cache-Control "no-store";
        add_header X-Robots-Tag "noindex, nofollow";
        add_header Profile-Update-Interval "12";
        add_header Profile-Title "base64:VHVubmVsIEV4YW1wbGU=";
        add_header Content-Disposition 'attachment; filename="tunnel-example"';
        add_header Subscription-Userinfo $sub_userinfo;
    }

    location ~ "^/s/(?<sub_token>[A-Za-z0-9_-]{32})\.json$" {
        limit_req zone=sub burst=20 nodelay;
        default_type application/json;
        charset utf-8;
        charset_types application/json;
        try_files /sip008/$sub_token.json =404;
        add_header Cache-Control "no-store";
        add_header X-Robots-Tag "noindex, nofollow";
    }

    location = /robots.txt {
        default_type text/plain;
        return 200 "User-agent: *\nDisallow: /\n";
    }

    location / {
        return 404;
    }
}

The parts that are easy to get wrong:

  • The map reads the usage file once, at load. The list files can change at any time, but new usage numbers only appear after a reload. Run the generator from cron, then nginx -t && systemctl reload nginx. A reload does not drop connections.
  • A token with no map entry sends no usage header. nginx leaves out a header whose value is empty. I checked this: a wrong token returns a bare 404 with no Subscription-Userinfo.
  • No always on add_header. Without it, nginx adds these headers only to successful responses (200, 206, redirects and a few others). With it, every 404 for a guessed token also carries Profile-Title and the other headers, and tells a scanner exactly what this host is. I tested both.
  • add_header does not merge. A location with its own add_header lines drops every add_header from the server level. That is why each location lists its own. See the nginx headers module docs.
  • charset_types application/json is needed for SIP008. Without it, nginx sends Content-Type: application/json with no charset, and SIP008 requires application/json; charset=utf-8.
  • Rate limits are per IP address. Many mobile users share one address behind carrier NAT, so keep the limit generous. 30 requests a minute with a burst of 20 is far more than any honest client needs.

Which headers should a subscription send?

Send the usage header with all four keys, the refresh interval, and a profile name. Clients ignore what they do not know:

Header Example What clients do with it
Subscription-Userinfo upload=0; download=1073741824; total=53687091200; expire=1798761600 show a traffic bar and expiry date. Bytes and Unix seconds; 0 means no limit. Send all four keys, because Hiddify ignores the header when one is missing.
Profile-Update-Interval 12 refresh interval in hours. Send a whole number.
Profile-Title base64:VHVubmVsIEV4YW1wbGU= the profile's name. The base64: form is safe for any language.
Content-Disposition attachment; filename="tunnel-example" a fallback name. For non-ASCII names use filename*=UTF-8'' with percent-encoding.
Support-Url https://t.me/your_support a support link in the app
Profile-Web-Page-Url https://sub.yourdomain.com/account a link to an account page
Cache-Control no-store for caches between you and the client

3x-ui sends Cache-Control: no-cache, no-store, must-revalidate on its subscription responses. no-store alone is enough for current caches. If a CDN sits in front of the host, read the caching section of the monitoring post, and turn off any bot challenge for this host. A client cannot solve an HTML challenge page, so it fails to import.

Give the host nothing to index and nothing to confirm. The config above already does most of it:

  • X-Robots-Tag: noindex, nofollow works for plain text, where a meta tag cannot.
  • robots.txt disallows the whole host. Use a separate host for subscriptions, so this rule never touches your main site.
  • Every other path returns 404, and so does a wrong token. Directory listing is off by default in nginx, so /b64/ lists nothing.
  • access_log off keeps tokens out of your logs and out of every log backup. If you need logs, write a log_format without $request_uri.
  • Never link to a subscription URL from a web page, and never post a real one in a support chat or a screenshot. A link that reaches a search engine can stay in its results after you revoke it.

How do I rotate servers without breaking clients?

Change the list in small steps and keep removed servers working for a while. Clients refresh on their own schedule. Profile-Update-Interval is a hint that some clients use as their default, and many users never refresh by hand. So:

  1. Add before you remove. Put the new server in the list first, wait at least one refresh interval, then take the old one out.
  2. Keep the old server or credential alive for two intervals after it leaves the list. With a 12-hour interval, that is a day. The monitoring post explains what happens to clients that refreshed before the change.
  3. Keep names stable. A user who picked de-fra-1 should find de-fra-1 after the refresh. In SIP008, keep each server's id the same across updates: clients use it to keep per-server settings.
  4. Watch the count. If tonight's generator run produces half as many links as last night's, stop and look before you publish.

How do I make a Shadowsocks subscription?

Serve a SIP008 JSON document. It lists servers as objects, not links, and has two optional usage fields:

{
  "version": 1,
  "servers": [
    {
      "id": "27b8a625-4f4b-4428-9f0f-8a2317db7c79",
      "remarks": "de-fra-1",
      "server": "vpn.yourdomain.com",
      "server_port": 8388,
      "password": "Wq3vT9pX2mK7sL4n",
      "method": "chacha20-ietf-poly1305"
    }
  ],
  "bytes_used": 1073741824,
  "bytes_remaining": 52613349376
}

Save it as /var/www/sub/sip008/<token>.json, and the second location in the nginx config serves it at /s/<token>.json with the exact content type the spec requires. The spec also requires HTTPS, and says clients must not ignore certificate errors, so use a real certificate. Leave out bytes_remaining when the user has no limit. If you send it, also send bytes_used. Add plugin and plugin_opts only for servers that use a plugin.

Shadowsocks servers can also go into the base64 list as ss:// links, which is the better choice when the same user also gets VLESS or Trojan servers.

Fetch it as a client would, from outside your network, and check the status, the headers, the body and every server in it:

SUB='https://sub.yourdomain.com/s/UhG0eSe6oBvbh-onp4ydKIctVxQnzOUo'
curl -sS -D headers.txt -o body.txt "$SUB"
head -1 headers.txt
grep -iE '^(content-type|cache-control|x-robots-tag|subscription-userinfo|profile-update-interval):' headers.txt
base64 -d < body.txt | grep -c '://'
curl -sS -o /dev/null -w '%{http_code}\n' 'https://sub.yourdomain.com/s/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'

The first request should show HTTP/2 200, all five headers, and the number of links you put in. The last one, a wrong token, must print 404. The subdecode.py script from the decode post also lists each link's protocol and name, and shows the expiry date as a client would.

Then import the link into one real client on a phone and check that the name, the traffic bar and the expiry date look right. Finally, test each server in the list with a real handshake. A link that decodes perfectly can still point at a server that does not answer. You can paste a single link into the free TunnelHQ tester for that.

Full disclosure: TunnelHQ can take the subscription URL itself. It adds every server behind it, keeps the list in sync when you rotate servers, and completes the real protocol handshake with each one from outside on a schedule, so a server you forgot to start shows up as an incident instead of a support ticket. Every plan has a 14-day free trial.