Apache – Conditional Reverse Proxy with RewriteCond

apache-2.4mod-rewriteproxypassreverse-proxyvirtualhost

I have a website that has a mobile version page, and since my website is behind the reverse proxy, I need a conditional function that can decide which version to be shown to visitors. I'm using Apache 2.4, the ProxyPass and ProxyReverse doesn't allowed to be inside of "If – Elseif" statement, so I tried with RewriteCond which is doesn't succeed.

Here is my VirtualHost

<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>

With the VirtualHost above, my reverse proxy only shows the mobile version. How to solve this? What do I need to add / change to make it work?

Best Answer

You can't do conditional reverse proxying mixing directives from different modules.

The correct way is using mod_rewrite all the way for this case:

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/

Note that the key here is the flag "P" to make mod_rewrite proxy instead of redirect.

Also note you still have to use ProxyPassReverse because this directive does something else entirely, that is dealing with redirects coming from the backend you are reverse proxying in the first place.