一个 Go语言反向代理的自我修养:可用、不裸奔、少惹事

Jayson
2026-10-20 / / 35 阅读 / 正在检测是否收录...
一个“看着能跑”的 GitHub 镜像,怎么一步步被改成“真能用、不裸奔、少惹事”的。附完整源码。文中域名统一用 example.com 代替,替换成你自己的即可。

写在前面

事情的起因特别简单:想用自己的域名反代 github.com,加速访问和 clone。

手头条件都齐了——*.example.com 泛解析、通配证书、Nginx 终止 TLS、一台小机器,再写个 Go 程序监听 127.0.0.1:18080,Nginx 把 443 反代进来,完事。

第一版代码跑起来那一刻,我觉得“这不就成了”。然后打开浏览器,页面白屏;git clone 一个仓库,GIT_CURL_VERBOSE=1 一看,请求直接飞到真实 github.com 去了。

接下来两天就是不断拆炸弹的过程。这篇博客把中间踩过的坑、最后能用的代码、以及一些不太好意思不提的风险,一次性写清楚。


一、第一版为什么“能跑但白屏”

第一版的核心逻辑是这样:根据 Host 前缀猜出目标域名,把响应体里的 GitHub 域名替换成代理域名,再把请求转发出去。

听起来合理,实际有两个致命问题。

1. 页面里的资源域名根本不在你的服务器上

代码会把页面里这些地址改写成新的子域:

  • github.githubassets.com → github-githubassets-com.example.com(CSS 和 JS)
  • avatars.githubusercontent.com → avatars-githubusercontent-com.example.com(头像)
  • api.github.com → api-github-com.example.com(页面动态数据)

如果你只配了 gh.example.com,这些子域根本没有解析记录,也没有证书。浏览器加载 CSS/JS 全部失败,页面自然白屏。

我一开始以为“加个泛解析就好了”,结果发现泛解析只解决了 DNS,证书还得是通配的。*.example.com 的证书只能覆盖一级子域,恰好这些映射出来的都是一级子域,勉强够用。再往下嵌套一层就废了。

2. git clone 根本没走你的代理

http.Client 默认会自动跟随 3xx 重定向。GitHub 对 info/refs、archive 下载这些路径经常返回 301/302,Location 指向真实域名。客户端拿到 Location 就直连过去了,你的代理只在第一跳出现了一下,后面全是真实 GitHub 在服务。

这个问题不修,代理等于没做。修法很简单:

CheckRedirect: func(req *http.Request, via []*http.Request) error {
    return http.ErrUseLastResponse
},

禁止自动跟随之后,还要把响应里的 Location 头按映射表改写成代理域名。两件事缺一不可。


二、继续拆:大文件、源码污染、子串误伤

白屏和重定向解决之后,问题还没完。

大文件 OOM

第一版对所有响应都 io.ReadAll,release 二进制、archive zip 动辄几百 MB,全部读进内存。小机器直接挂。

改成:文本类响应才缓冲改写,其余流式 io.Copy 直接转发。

源码被污染

raw.githubusercontent.com 返回 text/plain。第一版判断条件是 strings.Contains(contentType, "text/"),text/plain 命中了,源码里出现的 https://github.com 就被替换成代理域名,下载下来的文件内容跟原文件不一样了。

改成白名单:只处理 text/html、text/css、application/javascript、application/json、application/xml、image/svg+xml,并且 raw/gist 主机直接跳过改写。

子串误伤

原来的域名映射是个 map[string]string,Go 的 map 遍历顺序是随机的。github.com 正好是 github.community 的前缀,如果先替换了 github.com,github.community 就会变成 gh.example.community,一个根本不存在的域名。

改成切片,按原域名长度降序排,长的先替换,短的后面就不会误伤。

还有几个小问题

  • Nginx 反代后 r.Host 可能带 :18080,拼出来的 URL 带端口。得 net.SplitHostPort 去一下。
  • 没有 Host 后缀校验,泛解析下任意 xxx.example.com 都能白嫖你的出口 IP。
  • Access-Control-Allow-Origin: * 加 Allow-Credentials: true 是非法组合,浏览器会拒绝。页面同源,不需要跨域,直接删。
  • 所有响应都 Cache-Control: public, max-age=14400,API 和 HTML 也被缓存,容易串数据。HTML/JSON 用 no-cache,静态资源才缓存。
  • hop-by-hop 头没过滤,Connection、Transfer-Encoding、Upgrade 这些都原样转发,不规范。
  • r.URL.Path 是解码后的,%2F 会被破坏,得用 EscapedPath()。

到这一步,技术上算是能用了。但新的问题来了。


三、加密码:一个看起来简单、实际有坑的需求

需求是“访问要输密码”。最合适的方案是 HTTP Basic Auth:浏览器弹原生框,git clone 也会提示输入,不需要改前端。

写起来不难,但有三个点必须注意。

1. 认证通过后必须把 Authorization 头删掉再转发

Basic Auth 的凭据在请求头里,如果你不加处理直接转发给 GitHub,等于把密码明明白白送过去了。

for key, values := range r.Header {
    if isHopByHop(key) || strings.EqualFold(key, "Authorization") {
        continue
    }
    // ...
}

2. 密码比较要用常量时间比较

普通的 == 比较会因为长度和内容不同产生时序差异,理论上可以被利用来爆破密码。用 crypto/subtle 的 ConstantTimeCompare,先 sha256 再比,避免长度泄漏。

func checkAuth(r *http.Request) bool {
    user, pass, ok := r.BasicAuth()
    if !ok {
        return false
    }
    userOK := subtle.ConstantTimeCompare(sha([]byte(user)), sha([]byte(proxyUser))) == 1
    passOK := subtle.ConstantTimeCompare(sha([]byte(pass)), sha([]byte(proxyPass))) == 1
    return userOK && passOK
}

3. 必须走 HTTPS

Basic Auth 是明文 base64,不是加密。没有 TLS 等于把密码写在请求头里公开传输。程序只监听 127.0.0.1:18080,Nginx 终止 TLS 之后再反代进来,外部拿不到明文。


四、只主域认证:不然网页还是白屏

全站认证有个很隐蔽的问题。

页面里的头像、CSS、JS、API 请求打到的是不同子域。浏览器不会把主域的 Basic Auth 凭据自动带到子域去。img 标签、fetch、XHR 加载子域资源时不会弹框,直接 401 失败。

结果就是:你输了密码,主页面加载出来了,但所有资源全是裂图、样式全丢、动态数据空着。

解决办法:只对主域 gh. 要求密码,资源子域放行。

if hostPrefix == "gh." && !checkAuth(r) {
    w.Header().Set("WWW-Authenticate", `Basic realm="proxy"`)
    http.Error(w, "Unauthorized", http.StatusUnauthorized)
    return
}

这样打开 https://gh.example.com 会弹框,输一次密码页面就正常了;git clone https://gh.example.com/... 仍然要密码。

代价是资源子域无认证,但那些子域只代理静态资源和 raw 源码,不接触登录能力,被白嫖的风险远小于主域开放。

如果你只打算用 git clone、不看网页,全站认证也能用,反正资源加载失败不影响 clone。


五、隐藏指纹:别让扫描器一眼认出这是反代

无认证的反向代理是自动化扫描器的重点目标。即使你不公开域名,通过 IP 扫描和 Host 头爆破也能枚举出来。

我做了三层处理。

代码层:统一 404,不暴露原因

Host 不合法、域名未配置,原来返回的是 Domain not configured for proxy 这种明文。这个错误页本身就是指纹——固定文案、无认证、自定义反向代理,扫描器一眼就认出来。

改成统一返回 404 page not found,上游错误也统一 502 Bad Gateway,不带 %v 详情。

Nginx 层:return 444 直接断连

非 *.example.com 的 Host 直接关闭连接,不回任何数据。比 403/404 更隐蔽。

if ($host !~* ^([a-z0-9-]+)\.example\.com$) {
    return 444;
}

有个坑要注意:静态资源的 location 是正则 ~*,优先级高于 location /。如果只在 location / 里加校验,扫描器用非法 Host 访问 xxx.js 会走静态资源 location,绕过校验。两个 location 都要加。

可选层:IP 白名单

Nginx 层 allow 常用 IP、deny all,扫描器摸到 443 直接吃拒绝,连 404 指纹都拿不到。这是最强的一层,代价是换网络要改配置。


六、宝塔的 Nginx 默认片段:看着能用,其实缺东西

我用的是宝塔,它自动生成的 PROXY 片段长这样:

location ~* \.(gif|png|jpg|css|js|woff|woff2)$
{
    proxy_pass http://127.0.0.1:18080;
    proxy_set_header Host $host;
    ...
    expires 12h;
}
location /
{
    proxy_pass http://127.0.0.1:18080;
    ...
    add_header Cache-Control no-cache;
}

能跑,但对 git 和反代来说不够。

  • 缺 proxy_http_version 1.1。默认走 HTTP/1.0,git smart HTTP 的 keepalive 和 chunked 编码可能异常,clone 偶发失败。要加 proxy_http_version 1.1; 和 proxy_set_header Connection "";。
  • 缺流式转发。没有 proxy_request_buffering off 和 proxy_buffering off,大文件下载会被 Nginx 缓冲到磁盘,延迟高还占空间。
  • 缺超时配置。默认 60s,大仓库 clone 会被掐断。改成 proxy_read_timeout 300s。
  • 缺 client_max_body_size 0。默认 1m,如果你以后需要 push,直接 413。
  • 缓存头和后端打架。expires 12h 跟后端的 Cache-Control: public, max-age=14400 冲突,响应里会出现两个 Cache-Control,行为不确定。add_header Cache-Control no-cache; 又把所有响应(包括 zip、release 二进制)都变成 no-cache。干脆全删,缓存策略交给后端按 Content-Type 决定。
  • server_name 必须带泛解析。只写 gh.example.com 的话,资源子域会落到默认 server,页面还是白屏。要写 server_name gh.example.com *.example.com;。

改完之后的片段:

location ~* \.(gif|png|jpg|css|js|woff|woff2)$
{
    if ($host !~* ^([a-z0-9-]+)\.example\.com$) {
        return 444;
    }

    proxy_pass http://127.0.0.1:18080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_request_buffering off;
    proxy_buffering off;
    proxy_read_timeout 300s;
    client_max_body_size 0;
}

location /
{
    if ($host !~* ^([a-z0-9-]+)\.example\.com$) {
        return 444;
    }

    proxy_pass http://127.0.0.1:18080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_request_buffering off;
    proxy_buffering off;
    proxy_read_timeout 300s;
    client_max_body_size 0;
}

proxy_set_header Host $host; 绝对不能省。少了它,程序收到的是 127.0.0.1:18080,Host 后缀校验直接 404。


七、不用 systemd,用 screen

程序只监听 127.0.0.1:18080,外部访问不了,由 Nginx 反代。所以我没用 systemd,直接 screen。

启动脚本里有明文密码,权限必须 700,不然同机器其他用户能读:

cat > /opt/ghproxy/run.sh <<'EOF'
#!/bin/bash
cd /opt/ghproxy
export PROXY_USER='youruser'
export PROXY_PASS='your-strong-pass'
./ghproxy 2>&1 | tee -a /opt/ghproxy/proxy.log
EOF

chmod 700 /opt/ghproxy/run.sh

启动和查看:

screen -dmS ghproxy /opt/ghproxy/run.sh
screen -ls
tail -f /opt/ghproxy/proxy.log

重启:

screen -S ghproxy -X quit
screen -dmS ghproxy /opt/ghproxy/run.sh

screen 的局限是服务器重启后会话消失,程序不会自动起。加一条 cron:

@reboot sleep 30 && screen -dmS ghproxy /opt/ghproxy/run.sh

sleep 30 是等网络和 DNS 就绪,按需调整。


八、完整源码

package main

import (
    "crypto/sha256"
    "crypto/subtle"
    "fmt"
    "io"
    "log"
    "net"
    "net/http"
    "net/url"
    "os"
    "regexp"
    "sort"
    "strings"
    "time"
)

// 改成你自己的域名后缀
const allowedSuffix = ".example.com"

type domainMap struct {
    origin string
    prefix string
}

var domainMappings = []domainMap{
    {"avatars.githubusercontent.com", "avatars-githubusercontent-com."},
    {"github.githubassets.com", "github-githubassets-com."},
    {"collector.github.com", "collector-github-com."},
    {"api.github.com", "api-github-com."},
    {"raw.githubusercontent.com", "raw-githubusercontent-com."},
    {"gist.githubusercontent.com", "gist-githubusercontent-com."},
    {"assets-cdn.github.com", "assets-cdn-github-com."},
    {"securitylab.github.com", "securitylab-github-com."},
    {"www.githubstatus.com", "www-githubstatus-com."},
    {"git-lfs.github.com", "git-lfs-github-com."},
    {"githubusercontent.com", "githubusercontent-com."},
    {"github.global.ssl.fastly.net", "github-global-ssl-fastly-net."},
    {"github.community", "github-community."},
    {"github.io", "github-io."},
    {"cdn.jsdelivr.net", "cdn-jsdelivr-net."},
    {"api.npms.io", "api-npms-io."},
    {"npmjs.com", "npmjs-com."},
    {"codeload.github.com", "codeload-github-com."},
    {"github.com", "gh."},
}

func init() {
    sort.Slice(domainMappings, func(i, j int) bool {
        return len(domainMappings[i].origin) > len(domainMappings[j].origin)
    })
}

var (
    proxyUser string
    proxyPass string
)

func sha(b []byte) []byte {
    h := sha256.Sum256(b)
    return h[:]
}

func checkAuth(r *http.Request) bool {
    user, pass, ok := r.BasicAuth()
    if !ok {
        return false
    }
    userOK := subtle.ConstantTimeCompare(sha([]byte(user)), sha([]byte(proxyUser))) == 1
    passOK := subtle.ConstantTimeCompare(sha([]byte(pass)), sha([]byte(proxyPass))) == 1
    return userOK && passOK
}

// 统一通用 404,不暴露任何内部原因
func notFound(w http.ResponseWriter) {
    w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    w.WriteHeader(http.StatusNotFound)
    io.WriteString(w, "404 page not found\n")
}

func getProxyPrefix(host string) string {
    for _, m := range domainMappings {
        if strings.HasPrefix(host, m.prefix) {
            return m.prefix
        }
    }
    return ""
}

func getTargetHost(prefix string) string {
    for _, m := range domainMappings {
        if m.prefix == prefix {
            return m.origin
        }
    }
    return ""
}

func isTextContent(ct string) bool {
    ct = strings.ToLower(ct)
    return strings.Contains(ct, "text/html") ||
        strings.Contains(ct, "text/css") ||
        strings.Contains(ct, "application/javascript") ||
        strings.Contains(ct, "application/json") ||
        strings.Contains(ct, "application/xml") ||
        strings.Contains(ct, "image/svg+xml")
}

func isHopByHop(key string) bool {
    switch strings.ToLower(key) {
    case "connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
        "te", "trailers", "transfer-encoding", "upgrade", "host", "content-length":
        return true
    }
    return false
}

func rewriteAll(text, domainSuffix string) string {
    for _, m := range domainMappings {
        full := m.prefix + domainSuffix
        text = strings.ReplaceAll(text, "https://"+m.origin, "https://"+full)
        text = strings.ReplaceAll(text, "http://"+m.origin, "https://"+full)
        text = strings.ReplaceAll(text, "//"+m.origin, "//"+full)
        text = strings.ReplaceAll(text, `"`+m.origin+`"`, `"`+full+`"`)
        text = strings.ReplaceAll(text, `'`+m.origin+`'`, `'`+full+`'`)
    }
    return text
}

func modifyResponse(body []byte, contentType, hostPrefix, currentHostname string) []byte {
    if !isTextContent(contentType) {
        return body
    }
    // raw / gist 源码不要改写,避免污染下载内容
    if hostPrefix == "raw-githubusercontent-com." || hostPrefix == "gist-githubusercontent-com." {
        return body
    }
    text := string(body)
    domainSuffix := strings.TrimPrefix(currentHostname, hostPrefix)
    text = rewriteAll(text, domainSuffix)
    if hostPrefix == "gh." {
        text = strings.ReplaceAll(text, `"/`, `"https://`+currentHostname+`/`)
        text = strings.ReplaceAll(text, `'/`, `'https://`+currentHostname+`/`)
    }
    return []byte(text)
}

var proxyClient = &http.Client{
    Transport: &http.Transport{
        Proxy:                 http.ProxyFromEnvironment,
        DialContext:           (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
        TLSHandshakeTimeout:   10 * time.Second,
        ResponseHeaderTimeout: 30 * time.Second,
        IdleConnTimeout:       90 * time.Second,
        MaxIdleConns:          100,
        MaxIdleConnsPerHost:   20,
    },
    // 禁止自动跟随 302,否则 clone 会被踢回真实 github.com
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        return http.ErrUseLastResponse
    },
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
    hostname, _, err := net.SplitHostPort(r.Host)
    if err != nil {
        hostname = r.Host
    }
    hostname = strings.ToLower(strings.TrimSuffix(hostname, "."))

    // 非法后缀 / 未配置域名:统一 404,不暴露原因
    if !strings.HasSuffix(hostname, allowedSuffix) {
        notFound(w)
        return
    }
    hostPrefix := getProxyPrefix(hostname)
    if hostPrefix == "" {
        notFound(w)
        return
    }
    targetHost := getTargetHost(hostPrefix)
    if targetHost == "" {
        notFound(w)
        return
    }

    // 只对主域 gh. 要求密码;资源子域放行,否则网页加载不出来
    if hostPrefix == "gh." && !checkAuth(r) {
        w.Header().Set("WWW-Authenticate", `Basic realm="proxy"`)
        http.Error(w, "Unauthorized", http.StatusUnauthorized)
        return
    }

    pathname := r.URL.EscapedPath()
    re1 := regexp.MustCompile(`(/[^/]+/[^/]+/(?:latest-commit|tree-commit-info)/[^/]+)/https%3A//[^/]+.*`)
    pathname = re1.ReplaceAllString(pathname, "$1")
    re2 := regexp.MustCompile(`(/[^/]+/[^/]+/(?:latest-commit|tree-commit-info)/[^/]+)/https://[^/]+.*`)
    pathname = re2.ReplaceAllString(pathname, "$1")
    re3 := regexp.MustCompile(`(/[^/]+/[^/]+/(?:latest-commit|tree-commit-info)/[^/]+)/https:/[^/]+.*`)
    pathname = re3.ReplaceAllString(pathname, "$1")

    targetURL, err := url.Parse("https://" + targetHost + pathname)
    if err != nil {
        notFound(w)
        return
    }
    targetURL.RawQuery = r.URL.RawQuery

    req, err := http.NewRequest(r.Method, targetURL.String(), r.Body)
    if err != nil {
        http.Error(w, "Bad Gateway", http.StatusBadGateway)
        return
    }
    req.ContentLength = r.ContentLength

    for key, values := range r.Header {
        // 不把 Basic Auth 的 Authorization 转发给 GitHub
        if isHopByHop(key) || strings.EqualFold(key, "Authorization") {
            continue
        }
        for _, v := range values {
            req.Header.Add(key, v)
        }
    }
    req.Host = targetHost
    req.Header.Set("Host", targetHost)
    req.Header.Set("Referer", targetURL.String())
    req.Header.Set("Accept-Encoding", "identity")

    resp, err := proxyClient.Do(req)
    if err != nil {
        http.Error(w, "Bad Gateway", http.StatusBadGateway)
        return
    }
    defer resp.Body.Close()

    domainSuffix := strings.TrimPrefix(hostname, hostPrefix)
    contentType := resp.Header.Get("Content-Type")

    for key, values := range resp.Header {
        lk := strings.ToLower(key)
        if isHopByHop(lk) || lk == "content-encoding" {
            continue
        }
        if lk == "location" {
            for _, v := range values {
                w.Header().Add(key, rewriteAll(v, domainSuffix))
            }
            continue
        }
        for _, v := range values {
            w.Header().Add(key, v)
        }
    }
    w.Header().Del("Content-Security-Policy")
    w.Header().Del("Content-Security-Policy-Report-Only")
    w.Header().Del("Clear-Site-Data")

    if strings.Contains(contentType, "text/html") || strings.Contains(contentType, "application/json") {
        w.Header().Set("Cache-Control", "no-cache")
    } else {
        w.Header().Set("Cache-Control", "public, max-age=14400")
    }

    if resp.StatusCode == http.StatusNotModified || resp.StatusCode == http.StatusNoContent {
        w.WriteHeader(resp.StatusCode)
        return
    }

    // 非文本流式转发,避免大文件 OOM
    if !isTextContent(contentType) {
        if resp.ContentLength >= 0 {
            w.Header().Set("Content-Length", fmt.Sprintf("%d", resp.ContentLength))
        }
        w.WriteHeader(resp.StatusCode)
        if r.Method != http.MethodHead {
            io.Copy(w, resp.Body)
        }
        return
    }

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        http.Error(w, "Bad Gateway", http.StatusBadGateway)
        return
    }
    modified := modifyResponse(body, contentType, hostPrefix, hostname)
    w.Header().Set("Content-Length", fmt.Sprintf("%d", len(modified)))
    w.WriteHeader(resp.StatusCode)
    if r.Method != http.MethodHead {
        w.Write(modified)
    }
}

func main() {
    proxyUser = os.Getenv("PROXY_USER")
    proxyPass = os.Getenv("PROXY_PASS")
    if proxyUser == "" || proxyPass == "" {
        log.Fatal("必须设置 PROXY_USER 和 PROXY_PASS 环境变量")
    }

    // 只监听回环,外部由 Nginx 443 终止 TLS 后反代进来
    addr := "127.0.0.1:18080"
    http.HandleFunc("/", handleRequest)
    log.Printf("GitHub 代理启动在 %s,用户名 %s", addr, proxyUser)
    if err := http.ListenAndServe(addr, nil); err != nil {
        log.Fatal("服务器启动失败:", err)
    }
}

编译:

mkdir -p /opt/ghproxy && cd /opt/ghproxy
go mod init ghproxy
go build -o ghproxy main.go

记得把 allowedSuffix 从 .example.com 改成你自己的域名后缀。


九、验证清单

改完别急着用,按顺序跑一遍:

# 1. 主域不带密码 → 401
curl -I https://gh.example.com

# 2. 主域带密码 → 200/302
curl -u user:pass -I https://gh.example.com

# 3. 资源子域不带密码 → 200
curl -I https://avatars-githubusercontent-com.example.com

# 4. 未配置子域 → 通用 404,无明文原因
curl -I https://whatever.example.com

# 5. 非法 Host → 连接被重置(444)
curl -I -H "Host: evil.com" https://服务器IP

# 6. clone 不跳回真实 github.com
GIT_CURL_VERBOSE=1 git clone https://gh.example.com/torvalds/linux.git /tmp/linux-test 2>&1 | grep -i location

第 6 步如果看到 Location: https://github.com/... 原样返回,说明 CheckRedirect 或 Location 重写没生效,回去检查代码。


十、一些消不掉的问题

代码能降低“被滥用”和“被指纹识别”的风险,但有些东西不是改代码能解决的。

  • CT 日志是公开的。 申请通配证书时,域名会写进 Certificate Transparency 日志,任何人都能查。域名藏不住。
  • 资源子域无认证。 raw-githubusercontent-com.example.com 这些子域扫到就能用。虽然只代理静态资源和 raw 源码,不接触登录,但如果你连这个都不放心,可以改成全站认证,代价是网页白屏,只适合纯 clone 场景。
  • objects.githubusercontent.com 不能加进映射表。 release 下载会 302 到它,URL 带 AWS SigV4 签名,签名里包含 Host,改域名会 403。只能让它直连。如果你服务器的网络到不了它,release 下载就会失败。
  • Go 的 net/http 有已知反代相关漏洞。 响应走私(CVE-2026-78660)、查询参数走私这些,升级到 Go 1.27.2+/1.26.9+、golang.org/x/net 0.60.0+ 能解决大部分。

十一、必须说清楚的风险

写到这里,技术上算是完整了。但有一件事绕不过去,得说在前面。

反代 GitHub 这件事本身,踩在灰色地带。

GitHub 的 Acceptable Use Policies 明确禁止未经授权使用其基础设施代理流量。即使你不碰登录、不公开、只自己用,Abuse 投诉链条也不会因为代码写得好就放过你。

实际案例不少:有开发者反代 GitHub 后收到域名注册商的钓鱼告警邮件;有镜像站被 Netcraft 举报,即使站长“根本没公开过域名”,第二天就收到涉嫌钓鱼的通知;Cloudflare 收到 Abuse 报告后会同步给主机商和域名注册局,最坏结果是域名被停止解析、主机账号被封。

更麻烦的是 IP 关联。你的服务器出口 IP 和这个代理服务强绑定,如果你的代理被用来做异常流量,或者触发了 GitHub 的自动化风控,你自己的 GitHub 账号也可能被连带封禁。

所以:

  • 如果只是个人低频 clone 公开仓库,加密码、限 IP、不公开,风险相对可控。
  • 如果要给别人用,或者产生流量,建议重新评估。
  • 更稳妥的做法是只做 git smart HTTP 的透明代理,放弃整页 HTML 反代。网页反代依赖太多子域和重定向,维护成本高,也更容易被判定为仿冒。

写在最后

这套方案从“能跑但白屏、clone 绕回真实域名”,改到“主域加密码、资源子域放行、统一 404 隐藏指纹、Nginx 断连防扫描”,技术上能稳定用于个人 clone 和看公开页面。

回头看,最花时间的不是写代码,而是想清楚每一层为什么要这么改:

  • 禁止跟随重定向,是因为 clone 会绕路
  • 资源子域放行,是因为浏览器不会跨子域带 Basic Auth
  • 统一 404,是因为错误文案本身就是指纹
  • 两个 location 都加 Host 校验,是因为正则 location 优先级更高

这些点单看都不难,但少一个就会在某个场景下出问题。

代码解决的是可用性和滥用风险,解决不了反代本身的性质。如果只是自己用,加密码、限 IP、不公开,风险可控;如果要公开,建议三思。


本文记录的代码和配置仅用于个人学习与低频自用。请遵守 GitHub 可接受使用政策及所在地法律法规。

0