7

I'm looking for an equivalent of Redirect requests only if the file is not found? where instead of redirecting, I want it to do a ProxyPass to another server if a file is missing.

This didn't work too well since it will not handle requests that do not end with "/" e.g. https://site.trajano.net/trajano which goes to the proxy and redrects instead.

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.*) - [L]
RewriteRule (.*) https://trajano.github.io/%{REQUEST_URI} [P]

I tried the following from a different answer as well which works slightly better but what happens is it redirects to github rather than proxy.

RewriteCond %{DOCUMENT_ROOT}/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteRule (.*) - [S=2]
#
# Requested resource does not exist, do rewrite if it exists in /archive
RewriteCond %{DOCUMENT_ROOT}/archive/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/archive/$1 -d
RewriteRule (.*) /archive/$1 [L]
#
# Else
RewriteRule (.*) https://trajano.github.io/%{REQUEST_URI} [P]
Community
  • 1
  • 1
Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265

1 Answers1

6

Both mod_rewrite and mod_proxy need to be enabled. Place the following in a VirtualHost block (not inside a Directory directive or anything other than VirtualHost):

RewriteEngine on

RewriteCond %{DOCUMENT_ROOT}/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteCond %{REQUEST_URI} !=/
RewriteRule (.*) - [L]
#
# Else proxy
RewriteRule ^/(.*)$ https://trajano.github.io/$1 [P,QSA]
ProxyPassReverse / https://trajano.github.io/

The first Rewrite block handles files and directories that exist in which case it returns the original file block.

The next rewrite rule will handle the proxies. The ProxyPassReverse ensures that the Location being returned is rewritten back to the local server rather than the proxied server.

ggedde
  • 582
  • 5
  • 12
Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265
  • This worked great, but only if you have a request in the url. If you want it to work for "/" then you will need to add an additional RewriteCond under `RewriteCond %{DOCUMENT_ROOT}/$1 -d` and add `RewriteCond %{REQUEST_URI} !=/` – ggedde Oct 04 '22 at 05:44
  • not sure what you mean, but you can make an edit – Archimedes Trajano Oct 04 '22 at 13:00