6

I've seen this example:

RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
RewriteRule ^/(.*)$ balancer://app_cluster%{REQUEST_URI} [P,QSA,L]

I need a similar thing that will delegate to mod_proxy (i.e. do a ProxyPass) when a static file does not exist. Is it doable?

kaqqao
  • 163
  • 1
  • 5
  • May be I misunderstood your question, but this setup with the `P` flag seems right to me. The doc (http://httpd.apache.org/docs/2.2/en/rewrite/flags.html#flag_p) says `Use this flag (P) to achieve a more powerful implementation of the ProxyPass directive`. Do you need the load balancing or is it just the example? Where is this instruction located? – Zimmi Jan 02 '15 at 15:58
  • Hmm, I think you're right about the P directive... I should be able to get away with just that. The balancer is just an example, no actual need for it. This whole think would be in the root config (no virtual host) as I just need Apache to serve static files if they exist (for mocking purposes) or forward to Tomcat in all other cases. – kaqqao Jan 02 '15 at 23:35
  • I had tested this setup (without the load balancing) and it is ok. Just think to remove the first "/" of the RewriteRule (`^(.*)$`) if you put this in a or similar container... – Zimmi Jan 02 '15 at 23:51
  • Awesome! Thanks! Care to convert the comment into an answer so I can accept it? – kaqqao Jan 02 '15 at 23:56

1 Answers1

3

This setup with the P flag is the right one for what you want to do. The doc about the P flag states:

Use this flag (P) to achieve a more powerful implementation of the ProxyPass directive

Some things about the example: as mentioned by Andrew in his answer, the DOCUMENT_ROOT is not necessary.

The second is just to pay attention where these instructions are located: remove the first "/" of the RewriteRule (^(.*)$) if you put this in a or similar container...

And the P flag implies the L flag, so it is not used but may make it a bit clearer if we leave it. There is also a "/" needed after the web addres.

So it may become something like:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/(.*)$ http://somewhere/$1 [P,QSA,L]
Zimmi
  • 1,071
  • 7
  • 11
  • 1
    Note: This didn't work for me with Apache2 v2.4.29. However, the instructions at https://stackoverflow.com/a/43431369/293064 did end up working to achieve this effect. – Jay Taylor Jul 10 '18 at 16:15
  • See also https://stackoverflow.com/questions/43421049/proxy-requests-only-if-the-file-is-not-found/43431369 which has rewrite rules for this and adds `ProxyPassReverse / https://somewhere/` after them claiming it is needed. – Stephen Ostermiller Jan 26 '20 at 10:54