【问题标题】:Using mod_proxy to rewrite the URL shown to the user使用 mod_proxy 重写显示给用户的 URL
【发布时间】:2013-11-28 10:18:45
【问题描述】:

我有一个 WordPress 网站,我需要重写一些页面的 URL,以表明它们来自特定的子域以匹配现有的打印件。我正在尝试通过 htaccess 和 mod_proxy 执行此操作,并且正在接近,但需要一些帮助。

这是我现在拥有的代码,它有些工作:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^subdomain\.domain\.edu$ [NC]
RewriteRule ^ http://othersubdomain.domain.edu/folder1/folder2/folder3%{REQUEST_URI} [L,P]

如果我输入 subdomain.domain.edu,我会得到正确的页面(位于 http://othersubdomain.domain.edu/folder1/folder2/folder3)并且浏览器 URL 仍然写为 subdomain.domain.edu。这很好用!

问题在于内页。例如,如果我输入 subdomain.domain.edu/contact,我会被重定向到正确的页面,但 URL 不会保持重写,它会显示提供服务的完整 URL。

有人可以帮我重写内页的 URL 吗?我觉得我很接近!

【问题讨论】:

    标签: .htaccess rewrite subdomain mod-proxy


    【解决方案1】:

    好吧,您这里主要不是使用 mod_proxy。您正在使用 mod_rewrite 的代理标志。至少,您需要使用ProxyPassReverse 来确保URL 保持不变。

    此外,在您的用例中不建议使用 mod_rewrite。您的后端服务器返回的页面可能嵌入了直接引用 othersubdomain.domain.edu 的绝对 URL。您应该使用 mod_proxy 的 ProxyPass 或 ProxyPassMatch 以及 mod_proxy_html。如果您仍然无法弄清楚,请在 cmets 中告诉我。

    更新

    首先,花点时间坐下来阅读the complete documentation about mod_proxy。它是最强大的 apache 模块之一,深入学习它会有很长的路要走。其次,不要为此使用 .htaccess。

    我假设您为您的特定子域配置了虚拟主机。如果没有,您应该先配置它。现在,在您的虚拟主机配置中,添加以下行:

    <VirtualHost *:80>
        ServerName subdomain.domain.edu
    
        ProxyPass         / http://othersubdomain.domain.edu/folder1/folder2/folder3/
        ProxyPassReverse  / http://othersubdomain.domain.edu/folder1/folder2/folder3/
        ProxyPassReverseCookieDomain  othersubdomain.domain.edu subdomain.domain.edu
        ProxyPassReverseCookiePath  /folder1/folder2/folder3/  /
    </VirtualHost>
    

    上述配置指令将对http://subdomain.domain.edu/foo/bar 的请求代理到http://othersubdomain.domain.edu/folder1/folder2/folder3/foo/bar。当响应可用时,它的标头将被更改,以便用户可以看到它是从 subdomain.domain.edu 生成的。如果您的后端服务器生成任何 cookie(例如,如果用户必须登录),则需要 Cookie 指令。

    这将带您走很长的路。之后,如果您想更改页面内容、嵌入样式表或 javascript 中的链接,您应该参考mod_proxy_html 的文档。

    【讨论】:

    • ProxyPassReverse 在 htaccess 文件中不起作用,并且它仅在代理响应是重定向时重写 Location: 标头。它对页面内容中的链接没有任何作用。
    • @JonLin - 请参阅第二段 - 我建议首先使用 mod_proxy + 推荐使用 mod_proxy_html 来处理页面内容中的链接。可以在 .htaccess 文件中完成的任何操作都可以移动到服务器、虚拟主机或目录配置中。
    • 对不起,我主要是 IIS 和 .NET 的人。您对我应该添加的语法有什么建议吗?整个 Apache 世界让我很困惑。再次感谢您的帮助。
    • @user2994930 - 没问题。我将编辑我的答案以包含要使用的确切指令。
    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 2015-01-16
    • 2011-02-21
    • 2012-04-06
    • 2023-04-11
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    相关资源
    最近更新 更多