LoadinG

零成本内网穿透实战:使用Cloudflare Tunnel让本地网站全球可访问

本文阅读 6 分钟
首页 知识教程 正文

📖 前言

你是否遇到过这样的问题:在本地开发了一个网站,想让朋友或客户查看,却因为缺乏公网IP、路由器配置复杂而束手无策?传统的内网穿透工具要么收费,要么配置复杂。今天介绍的主角——Cloudflare Tunnel,将彻底解决这些问题。

⭐ Cloudflare Tunnel 核心优势

  • 完全免费 :无流量限制、无连接数限制
  • 无需公网IP :不需要路由器端口转发
  • 极致安全 :零信任网络架构,默认加密
  • 简单易用 :几条命令即可完成配置
  • 自动HTTPS :免费SSL证书自动配置

🛠️ 实战环境准备

  • 操作系统 :macOS(Windows/Linux类似)
  • 本地服务 :Nginx + PHP网站
  • 域名 :weianet.com(已在Cloudflare托管)
  • 目标 :让 https://test.weianet.com 全球可访问

第一:基础环境搭建

1.1 安装Homebrew(如未安装)

# 在终端执行安装命令
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# 配置环境变量(针对Apple Silicon芯片)
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"

1.2 安装并配置Nginx

# 安装Nginx
brew install nginx

# 启动Nginx服务
brew services start nginx

# 检查安装是否成功
curl -I http://localhost:8080

1.3 准备测试网站

# 创建网站目录
mkdir -p ~/Sites/Weianetcom

# 创建测试页面
cat > ~/Sites/Weianetcom/index.html << 'EOF'
<!DOCTYPE html>
<html>
<head>
    <title>Weianetcom测试站</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .container { max-width: 800px; margin: 0 auto; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎉 恭喜!内网穿透成功!</h1>
        <p>这是一个通过Cloudflare Tunnel暴露到公网的本地网站。</p>
        <p>服务器时间:<span id="time"></span></p>
        <script>document.getElementById('time').textContent = new Date().toLocaleString();</script>
    </div>
</body>
</html>
EOF

1.4 配置Nginx(关键步骤)

# 备份原始配置
sudo cp /opt/homebrew/etc/nginx/nginx.conf /opt/homebrew/etc/nginx/nginx.conf.backup

# 编辑Nginx配置
sudo nano /opt/homebrew/etc/nginx/nginx.conf

完整的Nginx配置内容:

# 指定运行用户和组(重要!避免权限问题)
user weianet staff;
worker_processes 1;

error_log  /opt/homebrew/var/log/nginx/error.log;
pid        /opt/homebrew/var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include       /opt/homebrew/etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /opt/homebrew/var/log/nginx/access.log main;
    sendfile on;
    keepalive_timeout 65;

    # 主服务器配置
    server {
        # 监听80端口(Cloudflare Tunnel默认连接端口)
        listen 80;
        # 匹配所有域名
        server_name _;
        
        # 网站根目录
        root /Users/weianetcom/Sites/Web;
        index index.html index.htm index.php;

        # 访问日志
        access_log /opt/homebrew/var/log/nginx/web.access.log main;
        error_log  /opt/homebrew/var/log/nginx/web.error.log;

        # 基础请求处理
        location / {
            try_files $uri $uri/ =404;
        }

        # 禁止访问敏感目录
        location ~ /\. {
            deny all;
            access_log off;
            log_not_found off;
        }

        # 静态资源缓存
        location ~* \.(jpg|jpeg|png|gif|css|js|ico)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
            access_log off;
        }
    }
}

保存并测试配置:

# 测试配置文件语法
sudo nginx -t
# 期望输出:syntax is ok, test is successful

# 重启Nginx使配置生效
sudo nginx -s stop
sudo nginx

# 验证本地访问
curl -I http://localhost

第二:Cloudflare Tunnel配置

2.1 安装Cloudflare Tunnel客户端

# 使用Homebrew安装
brew install cloudflared

# 验证安装
cloudflared --version

2.2 登录Cloudflare账户

# 执行登录命令,会在浏览器打开认证页面
cloudflared tunnel login

操作流程:

  • 命令执行后自动打开浏览器
  • 选择你要使用的域名(如 weianet.com)
  • 点击"授权"按钮
  • 认证成功后关闭浏览器页面

2.3 创建隧道

# 创建命名隧道
cloudflared tunnel create test-tunnel

# 查看隧道列表
cloudflared tunnel list

预期输出:

ID                                   NAME           CREATED              CONNECTIONS
39a19305-0c66-4a26-8a4d-162aa8e8ca3e test-tunnel   2025-01-01T10:00:00Z 0

记下隧道ID: 39a19305-0c66-4a26-8a4d-162aa8e8ca3e

2.4 配置隧道路由

# 创建配置目录
mkdir -p ~/.cloudflared

# 编辑配置文件
nano ~/.cloudflared/config.yml

配置文件内容:

# Cloudflare Tunnel 配置文件
tunnel: 39a19305-0c66-4a26-8a4d-162aa8e8ca3e  填写自己的ID
credentials-file: /Users/weianetcom/.cloudflared/39a19305-0c66-4a26-8a4d-162aa8e8ca3e.json  填写自己的ID

# 流量路由规则
ingress:
  # 规则1:将子域名指向本地Nginx
  - hostname: test.weianet.com
    service: http://localhost:80
  
  # 规则2:兜底规则,返回404
  - service: http_status:404

保存文件: 按 Ctrl+X → 按 Y → 按 Enter

2.5 配置DNS记录

# 将DNS记录指向隧道
cloudflared tunnel route dns test-tunnel test.weianet.com

或者手动在Cloudflare面板配置:

1.登录 Cloudflare 仪表板

2.选择域名 weianet.com

3.进入 DNS → 记录

4.添加CNAME记录:

  • 类型:CNAME
  • 名称:test
  • 目标:39a19305-0c66-4a26-8a4d-162aa8e8ca3e.cfargotunnel.com 填写自己的ID
  • 代理状态:已代理(橙色云朵)

第三:运行与测试

3.1 测试运行隧道

# 前台运行,查看实时日志
cloudflared tunnel run test-tunnel --loglevel info

期待的成功日志:

2025-01-01T10:00:00Z INF Registered tunnel connection connIndex=0 connection=xxxx ip=xxx.xxx.xxx.xxx location=XXX

3.2 多终端测试访问

保持隧道运行,分别测试:

测试1:本地访问

curl -I https://test.weianet.com

测试2:手机测试

测试3:让朋友帮忙测试

  • 将网址发给不同地区的朋友
  • 确认均可正常访问

3.3 设置为系统服务(开机自启)

# 创建系统服务文件
nano ~/Library/LaunchAgents/com.cloudflared.tunnel.plist

服务文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.cloudflared.tunnel</string>
    <key>ProgramArguments</key>
    <array>
        <string>/opt/homebrew/bin/cloudflared</string>
        <string>--config</string>
        <string>/Users/weianetcom/.cloudflared/config.yml</string>
        <string>tunnel</string>
        <string>run</string>
        <string>test-tunnel</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/weianetcom/cloudflared.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/weianetcom/cloudflared.log</string>
</dict>
</plist>

启用服务:

# 加载服务
launchctl load ~/Library/LaunchAgents/com.cloudflared.tunnel.plist

# 立即启动
launchctl start com.cloudflared.tunnel

# 检查状态
launchctl list | grep cloudflared

第四:故障排查手册

4.1 常见错误及解决方案

❌ 错误1:403 Forbidden
问题原因: Nginx权限配置错误
解决方案:

# 检查Nginx运行用户
ps aux | grep nginx

# 修改文件权限
sudo chmod -R 755 ~/Sites/Web/
sudo chown -R $(whoami):staff ~/Sites/Web/

# 在nginx.conf第一行添加
user weianetcom staff;

❌ 错误2:Error 1033 - Tunnel not found
问题原因: 隧道未运行或配置错误
解决方案:

# 检查隧道进程
ps aux | grep cloudflared

# 重新运行隧道
cloudflared tunnel run test-tunnel

# 检查配置文件
cat ~/.cloudflared/config.yml

4.2 日志检查命令

# 检查Nginx错误日志
tail -f /opt/homebrew/var/log/nginx/error.log

# 检查Nginx访问日志
tail -f /opt/homebrew/var/log/nginx/web.access.log

# 检查Tunnel日志
tail -f ~/cloudflared.log

4.3 服务状态检查命令

# 检查Nginx状态
ps aux | grep nginx
sudo nginx -t

# 检查Tunnel状态
cloudflared tunnel list
launchctl list | grep cloudflared

# 检查网络连接
curl -I http://localhost
curl -I https://test.weianet.com

第五:高级配置技巧

5.1 多服务配置

ingress:
  - hostname: web.weianet.com
    service: http://localhost:80
  - hostname: api.weianet.com
    service: http://localhost:3000
  - hostname: admin.weianet.com
    service: http://localhost:8080
  - service: http_status:404

5.2 自定义源端口

ingress:
  - hostname: test.weianet.com
    service: http://localhost:8080  # 自定义端口

5.3 路径重写规则

ingress:
  - hostname: app.weianet.cn
    path: "/api/*"
    service: http://localhost:3000

🎯 成功指标验证

完成所有步骤后,你应该能够:

✅ 本地访问 http://localhost 正常

✅ 通过域名 https://test.weianet.com 全球访问

✅ 手机4G/5G网络可访问

✅ 朋友在外地可正常访问

✅ 服务开机自启,无需手动维护

📚 总结

通过本教程,你已成功实现了:

🔄 本地Nginx服务配置优化

🌐 Cloudflare Tunnel内网穿透配置

🔒 免费HTTPS证书自动部署

🚀 全球访问能力搭建

⚙️ 系统服务自启配置

现在你的本地网站已经具备了企业级的全球访问能力,而且完全免费!有任何问题欢迎在评论区讨论。

文章采用:署名-非商业性使用-相同方式知识共享 署名 4.0 协议国际版 (CC BY-NC-SA 4.0) 许可协议授权。
免责声明:本页面资源来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系客服并出示版权证明以便删除。
分享
如何自建VPN?OpenVPN服务器搭建全攻略
« 上一篇 09-14

发表评论 Comment

您必须 后才能发表评论哦~
昵称
请输入您的昵称
邮箱
输入QQ邮箱可获取头像
网址
可通过昵称访问您网站
快捷回复: 验证码:
让大家也知道你的独特见解
已有 0 条评论

动态快讯

热门文章

QQ客服:3236485 QQ群号:530123520

在线时间:09:00-18:00

扫描二维码

联系官方客服微信号

扫描二维码

关注官方微信公众号