Rewritting .htaccess file to direct to files using a wildcard
.htaccess files are extremely useful in many cases for users who either do not have root permissions or for users who simply aren't comfortable in making changes in their web server's configuration file. Trying to debug .htaccess not working isn't always the easiest thing to do, however, hopefully by checking the discuss below mentioned about htaccess, , , , .htaccess common problems as well as the troubleshooting tips, you'll have a better grasp on what you may have to modify to get your .htaccess file running smoothly.Problem :Currently my html code points to
www.example.com/images/sub/ABCimage.jpg
www.example.com/images/sub/XYZimage.jpg
Due to a limit on number of files (9999) within the folder , I had to split images into different folders, and it looks like this:
/images/sub/ABC
ABCimage.jpg
ABCimage2.jpg
ABCimage3.jpg
/images/sub/XYZ
XYZimage.jpg
XYZimage2.jpg
XYZimage3.jpg
In other words, I have create folders based on first three letters of the image file. Can some help with writing an .htaccess expression to direct requests from /images/sub/ABCimage.jpg to /images/sub/ABC/ABCimage.jpg , but using the wildcard, so I don't have to write individual lines for each scenario.
The solution uses very much the same principle as the code sample in the first part of my answer to your earlier question, just with a minor tweak to the pattern.
Using mod_rewrite at the top of your .htaccess file in the document root:
RewriteRule ^images/sub/(([A-Z]3)[^/]*.jpg)$ /images/sub/$2/$1 [L]
This assumes the first 3 letters are A-Z (all uppercase). The image basename is at least 3 characters long. All images are .jpg.
A rewrite loop is avoided by using the regex [^/]* (0 or more non-slash characters) so as not to match the newly rewritten subdirectory. A regex of .* here would result in the rewritten URL being matched and a rewrite loop would ensue. eg. /images/sub/ABC/ABCimage.jpg would get rewritten (again) to /images/sub/ABC/ABC/ABCimage.jpg etc.
Note that the above rewrites unconditionally. If there is any chance that /images/sub/ABCimage.jpg could exist then you will likely need an additional filesystem check (unless there is another pattern to these files). However, that is best avoided here since file system checks are relatively expensive.
some images are in
A12format, and therefore folders will be in the same format. Basically, first three characters could be a mix of letters and digits.
Modify the character class to include digits 0-9:
RewriteRule ^images/sub/(([A-Z0-9]3)[^/]*.jpg)$ /images/sub/$2/$1 [L]
If the first character is always a letter, then you can be more specific if you wish and change the subpattern ([A-Z0-9]3) to ([A-Z][A-Z0-9]2)
Comments
Post a Comment