From 435784f863e16aff6e964551175570d61392fcc8 Mon Sep 17 00:00:00 2001 From: pengruiqi4374 <104544893+prq0705@users.noreply.github.com> Date: Sun, 4 Oct 2026 14:21:22 +0800 Subject: [PATCH] =?UTF-8?q?web=5Fbase=5Furl=20=E6=9C=AA=E4=BD=9C=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E9=AA=8C=E8=AF=81=E7=A0=81=EF=BC=9Aopen=5Fcaptcha=3Dt?= =?UTF-8?q?rue=20=E6=97=B6=E9=AA=8C=E8=AF=81=E7=A0=81=E4=BB=8D=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E6=A0=B9=E8=B7=AF=E5=BE=84=20/captcha/=EF=BC=8C?= =?UTF-8?q?=E5=AD=90=E8=B7=AF=E5=BE=84=E5=8F=8D=E4=BB=A3=E4=B8=8B=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E9=A1=B5=E9=AA=8C=E8=AF=81=E7=A0=81=20404?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 同时配置 `web_base_url=/nps` 与 `open_captcha=true` 时,登录页验证码图片的 URL 仍然从根路径请求,导致使用反代时验证码404 --- web/controllers/login.go | 17 +++++++++++++++-- web/routers/router.go | 4 ++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/web/controllers/login.go b/web/controllers/login.go index 0fc1d1f..86805ee 100755 --- a/web/controllers/login.go +++ b/web/controllers/login.go @@ -5,6 +5,7 @@ import ( "github.com/astaxie/beego/utils/captcha" "math/rand" "net" + "strings" "sync" "time" @@ -27,10 +28,22 @@ type record struct { lastLoginTime time.Time } -func init() { +// InitCaptcha registers the captcha image route and the create_captcha template +// function. The image URL prefix must include web_base_url, otherwise the login +// page would request the captcha from the site root and fail behind a reverse +// proxy that only forwards the web_base_url sub path. +// +// It must be called after beego.LoadAppConfig, so it cannot live in init(): +// package init() runs before main() loads conf/nps.conf, where web_base_url +// would still be empty. +func InitCaptcha() { // use beego cache system store the captcha data store := cache.NewMemoryCache() - cpt = captcha.NewWithFilter("/captcha/", store) + base := strings.TrimSuffix(beego.AppConfig.String("web_base_url"), "/") + if base != "" && !strings.HasPrefix(base, "/") { + base = "/" + base + } + cpt = captcha.NewWithFilter(base+"/captcha/", store) } func (self *LoginController) Index() { diff --git a/web/routers/router.go b/web/routers/router.go index e4add32..961a552 100755 --- a/web/routers/router.go +++ b/web/routers/router.go @@ -6,6 +6,10 @@ import ( ) func Init() { + // The captcha image path and its filter are built from web_base_url, so it + // has to be registered here (after the config is loaded) instead of in an + // init() function. + controllers.InitCaptcha() web_base_url := beego.AppConfig.String("web_base_url") if len(web_base_url) > 0 { ns := beego.NewNamespace(web_base_url,