Apache2 - 使用 mod_rewrite 代理到另一个域

Posted

技术标签:

【中文标题】Apache2 - 使用 mod_rewrite 代理到另一个域【英文标题】:Apache2 - Using mod_rewrite to proxy to another domain 【发布时间】:2015-07-23 21:27:56 【问题描述】:

我正在运行 Apache 2.4 并使用 mod_rewrite 来实现以下目标 - 我需要代理几个不同的内部站点,以便它们看起来托管在同一台服务器上。例如,我希望这样做的方式是使用http://myserver/osnews 形式的 URL 这将代理来自www.osnews.comhttp://myserver/slashdot 的内容,这将代理来自www.slashdot.org 的内容。我在我的 apache conf 文件中定义了以下重写规则:

RewriteCond %REQUEST_URI ^/osnews(/?.*) [NC]
RewriteRule ^/osnews(.*) http://www.osnews.com$1 [P]

RewriteCond %REQUEST_URI ^/slshdot(/?.*) [NC]
RewriteRule ^/osnews(.*) http://www.slashdot.org$1 [P]

问题在于这会破坏代理站点中的所有样式表和图像。我认为这是因为重写的 URL 的形式是 http://myserver/story/28554/Russia_unveils_homegrown_PC_microprocessor_chips 而不是 http://myserver/osnews/story/28554/Russia_unveils_homegrown_PC_microprocessor_chips

相反,如果我尝试这样的事情,它工作得很好(我没有将网站作为原始网址的一部分,所以http://myserver 将只是代理到http://www.osnews.com):

RewriteCond %HTTP_HOST ^myserver$ [NC]                                                          
RewriteRule ^ http://www.osnews.com%REQUEST_URI [P]  

所以,我需要指导的是如何在代理从http://osnews.com/some-resource 返回后保留 URL http://mysite/osnews/some-resource

谢谢!

【问题讨论】:

【参考方案1】:

所以,我使用 mod_proxy 而不是 mod_rewrite 来完成这项工作。我使用的配置(在 VirtualHost 上下文中)是:

    ProxyPass /osnews.com/ http://www.osnews.com/
    ProxyhtmlURLMap http://www.osnews.com /osnews.com
    #LogLevel debug proxy_html:trace5
    <Location /osnews.com/>
        ProxyPassReverse /osnews.com/
        ProxyHTMLEnable On
        ProxyHTMLExtended On
        ProxyHTMLURLMap ^/ /osnews.com/ R
        ProxyHTMLURLMap ^/css/(.*) /osnews.com/css/$1 Rc
        ProxyHTMLURLMap ^/images/(.*) /osnews.com/images/$1 Rc
        RequestHeader    unset  Accept-Encoding
    </Location>

需要注意的一点是,如果您在 Ubuntu 上使用 apache2(在我的例子中是 Lubuntu 15.04),默认情况下不提供 mod proxy_html 的配置文件。您需要创建它,然后使用a2enmod proxy_html 启用它。这篇文章总结的很好:http://ckdake.com/content/2008/reverse-proxying-with-apache-and-modproxyhtml.html。

我发现 ProxyHTMLExtended 输出过滤器没有正确映射 URLS 仍然存在一些问题。但我希望最终能解决这些问题。

【讨论】:

以上是关于Apache2 - 使用 mod_rewrite 代理到另一个域的主要内容,如果未能解决你的问题,请参考以下文章

apache2服务器mod_rewrite模块 开启方法[linux, ubuntu]

Apache 2.4 不使用适用于 2.2 的规则通过 mod_rewrite 进行代理

Ubuntu系统启用Apache Mod_rewrite模块

Apache如何开启Mod_rewrite模块以及PHPWind伪静态(全伪)

Debian/Ubuntu下安装Apache的Mod_Rewrite模块的步骤

启用mod_rewrite的Chevereto安装