BuildInvestFitness
BlogToolboxAbout
Build / How to Set Up Your Own VPN Using V2Ray

How to Set Up Your Own VPN Using V2Ray

2026-11-29Build5 min

The best time to plant a tree was 20 years ago. The second best time is now.

The reason I am writing this article is that I have discovered many friends working internationally are using highly unstable VPNs, or some are using company VPNs that fail to access high-quality overseas resources like Google or YouTube once they get home or use mobile data.

How can this problem be solved? The answer is to build your own VPN.

This article describes a method for setting up a VPN. I have been using this setup for years, and it is very stable and unaffected by any external events.

Once set up, it only costs about 160 RMB per year and can be shared by multiple people, so why bother buying other VPNs?

Preparation

  1. Domain Registration: You can buy the cheapest domain available; I recommend buying it at CloudFlare for easier subsequent configuration;

  2. Nginx: A powerful open-source library. Here, we mainly use its reverse proxy capability. Its power goes beyond just reverse proxying; many large companies use it for rate limiting, gateways, and handling high traffic;

  3. V2ray: An open-source core decoding and forwarding engine, which is the heart of this VPN system;

  4. CloudFlare Registration: A BAAS and serverless platform that provides capabilities for domain registration and secure access;

  5. VPS Purchase: Any cloud provider will do; buy the cheapest one. Configuration: CPU/RAM/Disk: 1 Core, 1GB, 100GB is sufficient.

I recommend two cost-effective cloud providers:

racknerd and hostinger: You can basically get a VPS for around 100 RMB per year, and this VPS can also be used for other services.

https://my.racknerd.com/aff.php?aff=18467

https://www.hostinger.com/hk?REFERRALCODE=KKVYIZHIWDF8

Why is it stable?

Architecture diagram of v2ray-based VPN
Architecture diagram of v2ray-based VPN

The underlying structure relies on the combination of open-source V2ray + Nginx reverse proxy + DNS resolution to complete the VPN setup. The reason this "Domain + Cloudflare + Nginx + V2Ray" combination is the classic, robust choice is that it essentially splits "encryption/camouflage, stealth, routing, and backend forwarding" into four independent layers of defense:

 What roles do the four major components play?

  1. Domain (e.g., .com) — "Legal House Number & HTTPS ID Card"    • Standard HTTPS/TLS encryption certificates can only be issued to domains (not to raw IPs). With a domain, every connection of yours goes through the standard 443 port and carries a legitimate domain SNI. From the outside, it looks just like you are browsing a normal website;

   • Architectural decoupling: If you need to change your VPS server in the future, just update the IP in your DNS settings; your phone and computer clients don't need any reconfiguring. Conversely, if you change your domain, you don't need to touch the server. 2. Cloudflare (CF "Little Orange Cloud" CDN) — "Stealth Shield & Traffic Pool"    • Hiding the real VPS IP: The client connects to Cloudflare's global edge nodes. The outside world cannot see your real source server IP, meaning even if your original IP is scanned or restricted, you can "come back to life" with a new shell;    • Automatically managing user-facing HTTPS certificates: CF issues and automatically renews legal certificates for your domain for free;

   • Extreme concealment: Countless normal enterprise websites and SaaS platforms worldwide use Cloudflare. Your encrypted WebSocket traffic is mixed in with a massive volume of normal business traffic, making it extremely difficult to identify in isolation. 3. Nginx (Listening on public 443 port) — "Front Desk Receptionist & Secret Path Router"    • External camouflage (anti-proactive detection): If any malicious scanner or browser tries to open your domain directly, Nginx will serve /var/www/html/index.html just like a normal website, showing no signs of the proxy hidden behind it;

   • Secret path routing: Only requests that meet the criteria of "accessing a specific random secret path (e.g., /b7e4a2f9) + initiating a WebSocket protocol upgrade" will be forwarded by Nginx to V2Ray internally;

   • Reusing 443 port: If you want to host a blog or API service on the same VPS later, Nginx can handle it easily. 4. V2Ray (Listening only to local 127.0.0.1:10086) — "Backend Core Decoding & Forwarding Engine"    • Never exposing public ports: It only listens on the local loopback address, so a full-port scan from the public internet will never find 10086;

   • Authentication and Outbound: After receiving the WebSocket data stream from Nginx, it verifies the client's UUID (password), decrypts the VMess encryption package, and uses the freedom module to request the target website you actually want to access, sending the results back along the same path.

How to deploy

The placeholders in this article such as your-domain.com, YOUR_VPS_IP, YOUR_UUID, and /your-secret-path should be replaced with your own domain, VPS public IP, and randomly generated secret parameters during actual deployment.

Overall traffic link

The entire request passes through four nodes in sequence:

Client: Initiates an encrypted request to port 443 of your-domain.com (protocol: VMess + WebSocket + TLS).

Cloudflare CDN: After enabling the "Little Orange Cloud" proxy, it hides the real VPS IP from the outside world, automatically maintains the legal HTTPS certificate for the client, and then sends the traffic back to your VPS on port 443.

Nginx on VPS: Listens on port 443. Accessing the root path / returns a static camouflage page; only requests accessing the secret path /your-secret-path that also trigger a WebSocket upgrade are forwarded internally to 127.0.0.1:10086.

V2Ray on VPS: Listens only on local 127.0.0.1:10086, verifies the client UUID, decrypts the traffic, and then accesses the target website via the freedom outbound.

Additionally, there are two auxiliary optimizations: TCP BBR optimizes throughput and packet loss resistance in high-latency cross-border networks; UFW firewall ensures the server only exposes three standard ports: 22 / 80 / 443.

Pre-deployment preparation

Before you begin, please prepare the following four pieces of information and replace the corresponding placeholders in the following commands:

your-domain.com: The domain you purchased and hosted on Cloudflare (a subdomain is also acceptable).

YOUR_VPS_IP: The public IPv4 address of your overseas VPS.

YOUR_UUID: A random UUID generated on the spot via command line in Step 3.

/your-secret-path: A random WebSocket path generated on the spot via command line in Step 3.

Full deployment steps (Ubuntu 24.04 as an example; other Linux distributions work similarly)

Step 1: Configure Cloudflare (DNS resolution + 15-year Origin Certificate) Host your domain on Cloudflare. Go to DNS -> Records, and add an A record: Set Name to @ (or a subdomain like node), set IPv4 address to your YOUR_VPS_IP, and ensure Proxy status is set to "Proxied" (the orange cloud icon).

Go to Network and confirm that WebSockets are enabled (usually enabled by default).

Go to SSL/TLS -> Origin Server -> Create Certificate, and create an origin certificate with 15-year validity (saving you from the hassle of failed 90-day short-term certificate renewals). Save the public key and private key; you will write them to /etc/ssl/cf_origin.pem and /etc/ssl/cf_origin.key on your VPS later.

Go to SSL/TLS -> Overview and set the encryption mode to Full (strict).

Step 2: Enable TCP BBR and configure UFW firewall

After logging into your VPS, execute the following commands in order to enable BBR acceleration and configure the firewall to allow only ports 22 / 80 / 443:

cat >> /etc/sysctl.conf << 'EOF'
net.core.default_qdisc=fq
net.ipv4.tcp_congestion_control=bbr
EOF
sysctl -p
sysctl net.ipv4.tcp_congestion_control

ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

Confirm that the output for tcp_congestion_control is bbr.

Step 3: Install V2Ray and generate a random key

Deploy using the official V2Fly installation script, and generate a random UUID and WebSocket path on the fly (please make a note of the values printed in the terminal):

bash <(curl -L https://raw.githubusercontent.com/v2fly/fhs-install-v2ray/master/install-release.sh)

NEW_UUID=$(cat /proc/sys/kernel/random/uuid)
NEW_PATH="/$(openssl rand -hex 4)"
echo "YOUR_UUID: $NEW_UUID"
echo "YOUR_SECRET_PATH: $NEW_PATH"

Edit /usr/local/etc/v2ray/config.json, replacing YOUR_UUID and /your-secret-path with the values generated above:

{
  "log": {
    "loglevel": "warning",
    "access": "/var/log/v2ray/access.log",
    "error": "/var/log/v2ray/error.log"
  },
  "inbounds": [
    {
      "port": 10086,
      "listen": "127.0.0.1",
      "protocol": "vmess",
      "settings": {
        "clients": [
          {
            "id": "YOUR_UUID",
            "alterId": 0
          }
        ]
      },
      "streamSettings": {
        "network": "ws",
        "wsSettings": {
          "path": "/your-secret-path"
        }
      }
    }
  ],
  "outbounds": [
    {
      "protocol": "freedom",
      "settings": {}
    }
  ]
}

Start V2Ray and enable it to run at startup:

systemctl enable --now v2ray
systemctl status v2ray --no-pager

Step 4: Install Nginx, prepare the camouflage page, and configure the reverse proxy

Install Nginx and ensure that a standard static web page exists at /var/www/html/index.html (Nginx comes with a default welcome page after installation, which you can also replace with your own personal static page). Then, save the origin server certificate public key generated in Step 1 from Cloudflare to /etc/ssl/cf_origin.pem, and the private key to /etc/ssl/cf_origin.key:

apt update && apt install -y nginx chmod 600 /etc/ssl/cf_origin.key

Create the Nginx site configuration file /etc/nginx/sites-available/v2ray (please replace your-domain.com and /your-secret-path with your own values):

server {
    listen 80;
    server_name your-domain.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name your-domain.com;

    ssl_certificate /etc/ssl/cf_origin.pem;
    ssl_certificate_key /etc/ssl/cf_origin.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    root /var/www/html;
    index index.html;

    location /your-secret-path {
        if ($http_upgrade != "websocket") {
            return 404;
        }
        proxy_redirect off;
        proxy_pass http://127.0.0.1:10086;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

The configuration above includes an additional check that returns a 404 for non-WebSocket requests, so that even if a regular browser accidentally visits this path, it will not expose proxy signatures.

Enable the site configuration and reload Nginx:

ln -sf /etc/nginx/sites-available/v2ray /etc/nginx/sites-enabled/v2ray
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx

Step 5: Client connection parameters

When creating a new node in the client, fill in the following parameters accordingly:

Protocol: VMess

Address: your-domain.com (or a Cloudflare optimized IP after speed testing)

Port: 443

UUID: The YOUR_UUID generated in Step 3

AlterID: 0

Network: ws (WebSocket)

Host: your-domain.com

Path: The /your-secret-path generated in Step 3

TLS: tls (SNI should be filled with your-domain.com)

Example:

{
  "log": {
    "access": "~/.V2rayU/v2ray-core.log",
    "loglevel": "info",
    "error": "~/.V2rayU/v2ray-core.log"
  },
  "inbounds": [
    {
      "port": "1080",
      "listen": "127.0.0.1",
      "protocol": "socks",
      "settings": {
        "udp": false,
        "auth": "noauth"
      }
    },
    {
      "port": "1087",
      "listen": "127.0.0.1",
      "protocol": "http",
      "settings": {
        "timeout": 360
      }
    }
  ],
  "outbounds": [
    {
      "tag": "proxy",
      "streamSettings": {
        "security": "tls",
        "wsSettings": {
          "path": "/b7e4a2f9",
          "headers": {
            "host": "todo:your domain"
          }
        },
        "network": "ws",
        "tlsSettings": {
          "allowInsecure": false,
          "serverName": "todo:your domain",
          "alpn": [],
          "fingerprint": "chrome"
        }
      },
      "protocol": "vmess",
      "mux": {
        "concurrency": 8,
        "enabled": false
      },
      "settings": {
        "vnext": [
          {
            "port": 443,
            "address": "todo:your domain",
            "users": [
              {
                "security": "auto",
                "id": "07266b38-7e4e-ca98-9f4e-7794a6fee413",
                "level": 0,
                "alterId": 0
              }
            ]
          }
        ]
      }
    },
    {
      "tag": "direct",
      "settings": {
        "domainStrategy": "UseIP",
        "userLevel": 0
      },
      "protocol": "freedom"
    },
    {
      "tag": "block",
      "settings": {
        "response": {
          "type": "none"
        }
      },
      "protocol": "blackhole"
    }
  ],
  "dns": {},
  "routing": {
    "rules": [],
    "domainStrategy": "AsIs",
    "balancers": []
  }
}

Step 6: How does the client verify that the configuration is successful? After filling in the parameters, verify step-by-step from the outside in using the following 4 steps. If all pass, the full link is established:

Verify your domain and camouflage page (turn off your proxy first): Access https://your-domain.com directly via a browser. If the static welcome page opens correctly and the address bar displays a valid HTTPS lock icon, it means your DNS resolution, Cloudflare proxy, and origin certificate are effective.

Then, access https://your-domain.com/your-secret-path directly. It should normally return a 404 Not Found, indicating that the stealth traffic-splitting rule is effective.

Test the "Real Connectivity Latency" in the client: Open your client (such as Clash, Shadowrocket, v2rayN, v2rayNG, etc.), select the newly created node, and click Test Real Connectivity Latency / URL Test (do not just look at the TCP Ping). As long as a normal millisecond latency appears (e.g., around 200ms, rather than a timeout or -1), it means the TLS handshake + WebSocket upgrade + UUID authentication have all passed.

Enable the proxy to verify the exit IP: Enable the proxy in your client (it is recommended to switch to global mode for testing first), and open https://ipinfo.io/json in your browser. (Or execute curl -x http://127.0.0.1:7890 https://ipinfo.io/json in a local terminal, replacing the port according to your client's actual local port).

If the returned IP displays as your own YOUR_VPS_IP and the region matches your VPS data center, it means the configuration is 100% successful.

Server log verification (optional): Execute tail -f /var/log/nginx/access.log on the VPS while opening a web page in the client. If you see a "GET /your-secret-path HTTP/1.1" 101 log from a Cloudflare edge IP, it confirms that the forwarding is working perfectly.

If real connectivity fails, prioritize checking the following 3 items:

Accessing the camouflage page reports a 525 / 526 error: Check if Cloudflare's SSL/TLS mode is set to Full (strict), and whether /etc/ssl/cf_origin.pem and cf_origin.key on the VPS are saved completely.

The camouflage page opens, but the client real connection times out: Focus on checking if the UUID and Path (check if the leading / is missing) are exactly the same as those on the server; additionally, the VMess protocol requires that the time difference between the client and the VPS does not exceed 90 seconds. You can run timedatectl on the VPS to confirm that the system time has been synchronized automatically.

Nginx logs show 502 Bad Gateway: This indicates that V2Ray is not running or the ports do not match. Run systemctl status v2ray on the VPS to check the service status and the 10086 port.

Common Troubleshooting Commands

If you need to check the running status after deployment, you can execute the following in the VPS terminal:

  1. View Nginx and V2Ray running status and listening ports
systemctl status nginx v2ray --no-pager
ss -tulpn | grep -E "nginx|v2ray"
  1. View real-time forwarding logs (seeing a 101 status code from a Cloudflare node IP indicates normal operation)
tail -f /var/log/nginx/access.log
  1. View V2Ray error logs
tail -f /var/log/v2ray/error.log

Client Software:

Different operating systems use different applications: