Proxy static content only for proxyed requests

apache-2.4reverse-proxystatic-content

I have an apache serving one local app on "/" with its static files on "/static"

And another app with mod_proxy:

ProxyPreserveHost On
ProxyPass "/example" "http://127.0.0.1:9090/"
ProxyPassReverse "/example" "http://127.0.0.1:9090/"

And this app does have static content on its own "/static" but when it comes through the proxy taques te files from the first one.

¿Is there any way to serve "/static" to eachone depending on were does the recuest comes from?

Best Answer

Given your example, I would expect the tomcat static files located at http://127.0.0.1:9090/static to be accessible under http://127.0.0.1/example/static when using the proxy.

Possible Solution 1
I think the best practice solution would be to change to use relative paths in the tomcat app instead of absolute path, so the static files used the latter path;

<img src="static/my_image.jpg"></img>

or server root relative;

<img src="/example/static/my_image.jpg"></img>

and that would correctly serve the images e.g.

http://127.0.0.1/example/static/my_image.jpg

possible solution 2
Rename the apache static files to something else, and explicitly proxy the /static path to tomcat;

# move the locate apache static files to somewhere else;
# http://127.0.0.1/static_apache etc
ProxyPass /static http://127.0.0.1:9090/static
ProxyPassReverse /static http://127.0.0.1:9090/static
ProxyPass "/example" "http://127.0.0.1:9090"
ProxyPassReverse "/example" "http://127.0.0.1:9090"

Also note:

Ordering ProxyPass Directives

The configured ProxyPass and ProxyPassMatch rules are checked in the order of configuration. The first rule that matches wins. So usually you should sort conflicting ProxyPass rules starting with the longest URLs first. Otherwise, later rules for longer URLS will be hidden by any earlier rule which uses a leading substring of the URL.

Possibly hacky solution

Detect whether the request was initiated from the tomcat app by inspected the referer header;

RewriteEngine on
# match the app in the referer before processing the rule
RewriteCond %{HTTP_REFERER} /example
# reverse-proxy the request to the back-end
RewriteRule ^/static(/.*)?$ http://127.0.0.1:9090/static$1 [P]

(I didn't test that last solution, as it would seem just a novelty way of doing things...)

Related Topic