【问题标题】:Apache ProxyPass with dynamic hostname具有动态主机名的 Apache ProxyPass
【发布时间】:2013-09-18 18:17:29
【问题描述】:
我正在尝试使用 Apache 作为网关反向代理到与请求的 http_host 同名的后端服务器。
例如:
ProxyPass / https://%{HTTP_HOST}/
ProxyPassReverse / https://%{HTTP_HOST}/
我在使用此设置时遇到错误。有什么建议吗?
【问题讨论】:
标签:
linux
apache
ubuntu
proxy
reverse-proxy
【解决方案1】:
要将 Apache ProxyPass 指令与动态主机名一起使用,您还需要使用 ModRewrite。
目标
对虚拟主机的所有请求都将通过 ProxyPass 和 ProxyPassReverse(也称为“Apache 网关”)发送到 %{HTTP_HOST}
这样做有意义的唯一原因是,如果您在 apache 服务器上有特定主机名的 localhost 条目
示例
本地主机文件
10.0.0.2 foo.bar.com
10.0.0.3 bar.bar.com
工作原理
- 客户端向 foo.bar.com 发出请求(dnslookup 是公共 IP...您的 APACHE SERVER)
- 您的 apache 服务器有一个 localhost 条目 10.0.0.2 用于 foo.bar.com(您网络上的其他服务器)
- 请求通过 ModRewrite 并附加 /path1,然后移交给 ProxyPass 和 ProxyPassReverse
- ProxyPass 和 ProxyPassReverse 在 ip 10.0.0.2 处将调用传递给 foo.bar.com
客户端请求 foo.bar.com ---反向代理到----> foo.bar.com/path1(在某些其他内部服务器上)
Apache 配置
<VirtualHost *:443>
Servername *
# Must not contain /path1 in path (will add /path1)
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/path1/.*
RewriteRule ^/(.*) https://%{HTTP_HOST}/path1$1 [NC,R=302,L]
# Must contain /path1 in path (will send request to the proxy)
RewriteEngine On
RewriteOptions Inherit
RewriteCond %{REQUEST_URI} ^/path1/.*
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [NC,P]
SSLEngine on
SSLProxyEngine On
ProxyRequests Off
ProxyPass / https://$1/
ProxyPassReverse / https://$1/
ProxyPreserveHost On
###################
# SSL Constraints #
###################
SSLProtocol -ALL +SSLv3 +TLSv1
# Choose cipher suites
SSLHonorCipherOrder On
SSLCipherSuite ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:!LOW:!SSLv2:!EXPORT
# SameOrigin The page can only be displayed in a frame on the same origin as the page itself
Header set X-Frame-Options SAMEORIGIN
SSLCertificateFile /etc/apache2/example.crt
SSLCertificateKeyFile /etc/apache2/example.key
SSLCertificateChainFile /etc/apache2/gd_bundle.crt
SetOutputFilter INFLATE;proxy-html;DEFLATE
</VirtualHost>
来源:http://brakertech.com/apache-proxypass-with-dynamic-hostname/
【解决方案2】:
没有办法像使用代理传递那样动态地反向代理。但是,您可以使用 mod_rewrite 的 P 标志来实现。与ProxyPassReverse 相同,你不能使用%{HTTP_HOST},然而,因为主机名相同,你根本不需要它。只需要:
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [L,P]
您可能遇到的一个问题是,由于 DNS 将代理服务器解析为某个 IP,因此代理服务器必须知道相同的 DNS 主机名不解析到自己并实际解析到后端服务器(服务器代理到),否则会导致循环。