如何在同一localhost配置反向代理至两个不同站点?
反向代理多域名配置问题解决
问题场景
当前httpd.conf配置如下:
SSLProxyEngine on ProxyPassMatch ^/(.*)$ https://mysite1.com/$1 ProxyPassReverse ^/(.*)$ https://mysite1.com/$1
启动httpd后,访问http://localhost可正常跳转至https://mysite1.com首页,但点击首页按钮后,浏览器会直接跳转到https://my-OTHER-site1.com/oauth2/...,需要同时为这两个域名配置反向代理。
用户尝试过的无效配置
配置1:重复匹配根路径
SSLProxyEngine on ProxyPassMatch ^/(.*)$ https://mysite1.com/$1 ProxyPassReverse ^/(.*)$ https://mysite1.com/$1 ProxyPassMatch ^/(.*)$ https://my-OTHER-site1.com/$1 ProxyPassReverse ^/(.*)$ https://my-OTHER-site1.com/$1
配置2:按路径区分(实际场景补充)
实际首页地址为https://site1.mydoamin.com,认证跳转地址为https://site2.mydoamin.com/oauth2/auth?client_id..,用户尝试的配置:
ProxyPassMatch ^/(.*)$ https://site1.mydoamin.com/$1 ProxyPassMatch ^/oauth2/(.*)$ https://site2.mydoamin.com/$1
正确配置方案
核心逻辑:Apache代理规则从上到下匹配,需将更具体的路径规则放在前面,同时配合ProxyPassReverse修正响应头,避免浏览器直接跳转到真实域名。
针对实际场景的推荐配置:
SSLProxyEngine on # 优先匹配oauth2路径,转发到认证站点 ProxyPass /oauth2 https://site2.mydoamin.com/oauth2 ProxyPassReverse /oauth2 https://site2.mydoamin.com/oauth2 # 剩余所有请求转发到首页站点 ProxyPass / https://site1.mydoamin.com/ ProxyPassReverse / https://site1.mydoamin.com/
配置说明
- 用
ProxyPass替代ProxyPassMatch更简洁,适合固定路径前缀的场景 - 必须将具体路径规则(如
/oauth2)放在根路径规则之前,否则根路径会优先匹配所有请求,导致后续规则失效 ProxyPassReverse需与每个ProxyPass对应,作用是修改后端返回的Location等响应头,将真实域名替换为代理地址(localhost),确保浏览器始终通过代理访问,不会直接跳转至真实站点
如果坚持使用ProxyPassMatch,可参考以下配置:
SSLProxyEngine on ProxyPassMatch ^/oauth2/(.*)$ https://site2.mydoamin.com/oauth2/$1 ProxyPassReverse ^/oauth2/(.*)$ https://site2.mydoamin.com/oauth2/$1 ProxyPassMatch ^/(.*)$ https://site1.mydoamin.com/$1 ProxyPassReverse ^/(.*)$ https://site1.mydoamin.com/$1
注意需保留oauth2路径前缀,避免转发时丢失路径信息。
内容的提问来源于stack exchange,提问作者user584018
相关产品推荐
相关产品推荐

