Apache redirect 404 for only the files that are not found?
-
11-07-2019 - |
Question
What I'm looking to do is basically take all requests to a directory, and if the file exists, send it. If not, send it from the parent directory (assume it exists there). The files are large and there can be a lot, and the subdirectories will change frequently, so filesystem links isn't a great way to manage. Is there some Apache config way of doing this? e.g.
/path/file0
/path/file1
/path/sub1/fileA
/path/sub1/fileB
/path/sub1/fileC
/path/sub2/fileA
/path/sub2/fileB
/path/sub2/fileC
So, if a request comes in for /path/sub1/fileB
they get /path/sub1/fileB
(normal-case). If a request comes in for /path/sub1/file0
they get /path/file0
(special-case).
Or maybe there's a way in PHP, if I could have Apache redirect all requests in one folder to a specific php file that checks if the file is present and if not checks 'up' a folder?
Thanks.
Solution
You could use mod_rewrite to do that:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^path/[^/]+/([^/]+)$ path/$1 [L]
This rule will rewrite a request of /path/
foo
/
bar
to /path/
bar
only if /path/
foo
/
bar
is not a regular file.
OTHER TIPS
Yes, PHP can redirect to a parent directory.