RewriteRule转发至localhost后重定向指向本地而非原URL的解决办法
解决反向代理后后端重定向到localhost而非原始域名的问题
方案一:传递原始请求头给后端(推荐)
后端生成错误重定向URL的核心原因是:反向代理时默认会把Host头替换为localhost:5000,后端基于这个Host生成重定向地址,自然会指向localhost。你可以通过.htaccess配置,把原始请求的Host和协议传递给后端,让它生成正确的重定向链接。
在现有Rewrite规则前添加以下配置:
# 传递原始请求的Host头给后端 RequestHeader set Host "%{HTTP_HOST}" env=!Proxy # 传递原始请求的协议(HTTP/HTTPS)给后端 RequestHeader set X-Forwarded-Proto "https" env=HTTPS RequestHeader set X-Forwarded-Proto "http" env=!HTTPS
保留你原有的Rewrite规则:
RewriteEngine On RewriteRule "^(.*)$" http://localhost:5000/$1 [P,NE,L,QSA]
配置生效后,后端会基于收到的真实Host(example.com)和协议(https)生成重定向URL,直接返回https://example.com/login给客户端。
方案二:修改后端返回的重定向响应(兜底方案)
如果无法调整后端逻辑,你可以通过.htaccess拦截后端返回的重定向响应,将其中的localhost:5000替换为你的真实域名。
方法1:使用mod_substitute替换响应内容
RewriteEngine On RewriteRule "^(.*)$" http://localhost:5000/$1 [P,NE,L,QSA] # 针对指定类型的响应,替换URL中的localhost:5000 AddOutputFilterByType SUBSTITUTE text/html text/plain text/xml application/json application/javascript Substitute "s|http://localhost:5000/|https://example.com/|ni"
方法2:使用mod_headers修改Location响应头
RewriteEngine On RewriteRule "^(.*)$" http://localhost:5000/$1 [P,NE,L,QSA] # 直接修改重定向的Location头 Header edit Location "^http://localhost:5000/(.*)$" "https://example.com/$1"
这两种方法都会把后端返回的Location: http://localhost:5000/login修改为Location: https://example.com/login,客户端收到后就会跳转到正确地址。
内容的提问来源于stack exchange,提问作者incarnadine
相关产品推荐
相关产品推荐

