Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache rewrite if file doesn't exist, check another directory

I have tried to find a solution to this but just have not found the right examples for my need.

I have some images in this type of path: /container/2011/08/myfile.ext. I have to move some of the files from that path to one like this: /container/newdir/2011/08/myfile.ext. The ONLY change will be that some files will move to the "newdir" part of the path, but the rest of the path structure is the same.

I am trying to figure out how to create an Apache/htaccess re-write that will first check for the file in the original location /container/2011/08/myfile.ext, if not found, check in the new location /container/2011/08/myfile.ext if not found return a standard 404.

I have found solutions for process and other redirections, but not the entire path. Since, of course, the items in container are date specific, I need something that would take the path to the file being requested, if not found in requested location, check new location and if not found there, send the normal 404. So, it's not just a single file type failover, but something more dynamic.

Can anyone shed some light on how I might go about this?

like image 250
Andy Maxx Avatar asked Aug 06 '11 21:08

Andy Maxx


2 Answers

RewriteCond %{REQUEST_URI} ^/container/\d{4}/\d{2}/.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(container)(/\d{4}/\d{2}/.+)$ $1/newdir$2

If /container/2011/08/foo.bar is requested, but doesn' exist, it will rewrite to /container/newdir/2011/08/foo.bar. And if it doesn't exist there too, it should result in a 404.

\d represents a digit and {x} for repeating x times.

like image 54
Floern Avatar answered Nov 07 '22 05:11

Floern


This is a more generic response but will hopefully help with a solution. In our CMS, we have a single /images folder and the CSS will always reference that directory but I wanted to be able to organise the images locally into sub-directories yet still resolve to the root /images folder as referenced in the CSS.

In the example below, I capture the file name and store it into the environmental variable FILENAME. Then the rewrite conditions are subsequently stepped through, checks the file exists in the available folders /icons and /sprites before performing a rewrite.

RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} (([a-zA-Z0-9\-\_\ \.]+)\.(gif|jpg|png|jpeg|swf))$
RewriteRule .* - [ENV=FILENAME:%1]

RewriteCond %{DOCUMENT_ROOT}/assets/images/sprites/%{ENV:FILENAME} -f
RewriteRule ([a-zA-Z0-9\-\_\ \.]+)\.(gif|jpg|png|jpeg|swf)$ assets/images/sprites/$1.$2 [L]

RewriteCond %{DOCUMENT_ROOT}/assets/images/icons/%{ENV:FILENAME} -f
RewriteRule ([a-zA-Z0-9\-\_\ \.]+)\.(gif|jpg|png|jpeg|swf)$ assets/images/icons/$1.$2 [L]
like image 26
Onshop Avatar answered Nov 07 '22 04:11

Onshop