【问题标题】:Apache Conditional Proxy passApache 条件代理通行证
【发布时间】:2019-11-27 09:35:23
【问题描述】:

我对服务器没有太多经验。所以,这可能是一个愚蠢的问题。目前在我的 Apache 服务器 vim /etc/apache2/sites-enabled/000-default.conf 文件中,我有一个如下的 proxypass。

    ProxyPass        /phpmyadmin !
    ProxyPass / http://localhost:8080/
    ProxyPassReverse / http://localhost:8080/

我想为以下场景实现条件代理传递

如果网址中包含?_escaped_fragment_=,如以下网址

http://localhost/web/?_escaped_fragment_=/health

我希望将此 URL 重定向到具有不同端口的 URL,例如下面的 URL,

http://localhost:8082/web/?_escaped_fragment_=/health

如果网址不包含?_escaped_fragment_=,如下面的网址,

http://localhost/web/#!/health

我之前提到的重定向到端口 8080 的代理传递应该会发生。这是什么代码?

【问题讨论】:

标签: apache .htaccess proxypass


【解决方案1】:

由于 ProxyPass 不能进入 If 语句,您需要使用 mod_rewrite 进行代理/重定向,并使用 RewriteCond 过滤查询字符串。

由于查询字符串不会按请求更改,这里是一个粗略的示例:

RewriteEngine on
RewriteCond %{QUERY_STRING} ^_escaped_fragment_ [NC]
RewriteRule ^/(.*) http://localhost:8082/$1 [QSA,P,L]
RewriteRule ^/(.*) http://localhost:8080/$1 [P,L]
ProxyPassReverse / http://localhost:8080/
ProxyPassReverse / http://localhost:8082/

这意味着,如果 query_string 与字符串“_escaped_fragment_WHATEVERHERE”匹配,则将所有内容代理到目标端口 8082 并附加添加的任何查询字符串。

对于其他情况,代理将代理到 localhost:8080。

请注意,我添加了 QSA,它是一个标志,表示在原始请求中附加任何查询字符串,但为了清楚起见,我添加了它,因为在这种情况下,mod_rewrite 无论如何都会默认执行此操作。我在下面添加的重写标志链接中提供了有关它的更多信息。

您可以使这个示例更加具体,例如 last rewrite 将采用任何其他查询字符串,如果您不希望您可以更早地使用更详细的 rewritecond 或使用另一个 rewritecond 将其过滤掉。

有关更多详细信息,官方文档是这样说的: Rewrite Flags mod_rewrite

【讨论】:

  • 我使用了这个重写规则之王。但我无法实现这一点,因为浏览器中的 URL 也会自动更改为 localhost,这不适用于我的实现。我希望浏览器中的 URL 相同。我不能使用 IfDefine 检查条件并定义端口号。我试过这样做,但它不起作用。当我尝试在 if 中定义一个变量时,它给出了一个错误。
  • 如果您添加一个关于页面何时返回为localhost 或类似名称的示例,那么我可能会提供帮助。这些重写根本不会影响 url 中的主机名,并且您描述的问题与它们无关,您可能只是缺少 ProxyPassReverse 条目,如添加:ProxyPassReverse / http://localhost:8080/ProxyPassReverse / http://localhost:8082/。让我修正答案以添加这些。
  • @ezra-s,我想做类似RewriteRule ^/(.*) http://localhost:8080/$1 [P,L] ProxyPassReverse /$1 http://localhost:8080/ 的事情,我想将RewriteRule 中的匹配文本添加到ProxyPassReverse。我该怎么做?
  • "ProxyPassReverse / localhost:8080" 匹配后端在重定向中发回的所有可能的 url-path,因此您不需要像您描述的那样。
猜你喜欢
  • 2020-03-18
  • 2010-12-11
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
  • 2014-12-14
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
相关资源
最近更新 更多