使用 RewriteCond 的 Apache 條件反向代理

使用 RewriteCond 的 Apache 條件反向代理

我有一個具有行動版本頁面的網站,由於我的網站位於反向代理後面,因此我需要一個條件函數來決定向訪客顯示哪個版本。我使用的是 Apache 2.4,ProxyPass 和 ProxyReverse 不允許位於「If - Elseif」語句內,因此我嘗試使用 RewriteCond,但沒有成功。

這是我的虛擬主機

<VirtualHost *:80>
ServerName MyWebsite.com
ServerAlias www.ReverseProxy/ ReverseProxy/m/
ProxyPreserveHost On
RewriteEngine On
RequestHeader set "Host" "MyWebsite.com"

#Show mobile version if visitors used mobile device
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|googlebot-mobile|iemobile|ipad|iphone|ipod|opera mobile|palmos|webos" [NC]
ProxyPass / http://MyWebsite.com:80/m/
ProxyPassReverse / http://MyWebsite.com:80/m/

#Show desktop version if not a mobile device
RewriteCond %{HTTP_USER_AGENT} "!(android|blackberry|googlebot-mobile|iemobile|ipad|iphone|ipod|opera mobile|palmos|webos)" [NC]
ProxyPass / http://MyWebsite.com:80/
ProxyPassReverse / http://MyWebsite.com:80/
</VirtualHost>

使用上面的 VirtualHost,我的反向代理僅顯示行動版本。怎麼解決這個問題呢?我需要添加/更改什麼才能使其正常工作?

答案1

您無法對來自不同模組的條件反向代理混合指令進行操作。

對於這種情況,正確的方法是始終使用 mod_rewrite :

RewriteCond %{HTTP_USER_AGENT} "android|blackberry|googlebot-mobile|iemobile|ipad|iphone|ipod|opera mobile|palmos|webos" [NC]
RewriteRule ^/(.*) http://MyWebsite.com:80/m/$1 [P,L]
ProxyPassReverse / http://MyWebsite.com:80/m/

請注意,這裡的關鍵是標誌“P”,使 mod_rewrite 代理程式而不是重定向。

另請注意,您仍然必須使用 ProxyPassReverse,因為該指令完全執行其他操作,即處理來自您首先進行反向代理的後端的重定向。

相關內容