Nginx 在本地跑网站,Cloudflare Tunnel 把外网请求通过加密隧道转发到你的电脑。不需要公网 IP。
用户 → example.com → Cloudflare → 加密隧道 → 本地 Nginx(:80) → /www/
Nginx 接收请求、服务静态文件、加安全头。Cloudflare Tunnel 加密转发、不暴露端口。
从 nginx.org 下载 Windows 稳定版,解压到 Server/nginx/。
C:/path/to(正斜杠)。worker_processes 1;
events { worker_connections 1024; }
http {
include mime.types; # 必须有,否则 CSS/JS 加载不了
default_type application/octet-stream;
sendfile on; keepalive_timeout 65;
gzip on; gzip_vary on; gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css ... font/truetype image/svg+xml;
server {
listen 80;
server_name example.com www.example.com localhost;
root C:/Users/YourName/Server/www; # 正斜杠
index index.html;
error_page 404 /404.html;
location / { try_files $uri $uri/ =404; }
}
}
# 先检查语法 nginx.exe -t -p "C:/Users/YourName/Server/nginx" # 输出 syntax is ok 后再启动 nginx.exe -p "C:/Users/YourName/Server/nginx" # 验证 netstat -ano | findstr ":80" # 应看到 LISTENING curl http://localhost # 应返回 404(还没首页)或 200
nginx -t 显示 syntax is ok 但没启动,可能是 MSYS/bash 的问题。换 PowerShell 运行。放到 Server/cloudflared/。
cloudflared tunnel login
自动打开浏览器授权。成功后 ~\.cloudflared\cert.pem 生成。
cloudflared tunnel create my-tunnel
返回 UUID。同时 ~\.cloudflared\<UUID>.json 凭证文件生成。
cloudflared tunnel route dns my-tunnel example.com cloudflared tunnel route dns my-tunnel www.example.com
编辑 ~\.cloudflared\config.yml:
tunnel: <UUID>
credentials-file: C:\Users\YourName\.cloudflared\<UUID>.json
ingress:
- hostname: example.com
service: http://localhost:80
- hostname: www.example.com
service: http://localhost:80
- service: http_status:404
cloudflared tunnel --protocol http2 run my-tunnel
--protocol http2,强制 TCP 避免 UDP 被干扰。用管理员权限编辑 C:\Windows\System32\drivers\etc\hosts,添加:
127.0.0.1 example.com 127.0.0.1 www.example.com
之后本机访问域名直接走 Nginx,不绕 Cloudflare。
Server/ ├── nginx/ ← Nginx ├── www/ ← 网站文件(HTML/CSS/字体) │ └── index.html ← 主页 └── cloudflared/ ← cloudflared.exe
Nginx 的 root 指向 www。更多页面按自己需求添加。CSS 改后加 ?v=N 版本号。
@echo off title VIDDsys Server @start "" /B "C:\Users\YourName\Server\nginx\nginx.exe" -p "C:\Users\YourName\Server\nginx" @"C:\Users\YourName\Server\cloudflared\cloudflared.exe" tunnel --protocol http2 run my-tunnel @taskkill /f /im nginx.exe >nul 2>&1
黑窗开着=服务在跑,关窗=全停。bat 必须 CRLF 换行。
nginx -t -p "C:/Users/YourName/Server/nginx" # 语法检查 Stop-Process -Name nginx -Force # 全杀 Nginx netstat -ano | findstr ":80" # 端口检查
-s reload 后旧进程没退出。PowerShell Stop-Process -Name nginx -Force 全杀。
net stop w3svc /y + sc config w3svc start= disabled。
nginx.conf 缺少 include mime.types;。检查 conf/mime.types 是否存在。
依次排查:Nginx 在跑吗?config.yml 路径对吗?隧道 ID 填对了吗?加 --protocol http2。
hosts 文件没配或配错。检查 ping example.com 是否返回 127.0.0.1。
路径加 ?v=N 递增版本号。Cloudflare 和 Nginx 都靠它缓存。
换行必须是 CRLF,LF 换行 cmd.exe 不识别。