问题原文
原帖链接 · jcmaad · CC BY-SA 4.0
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.
已采纳解答
原帖链接 · MrWhite · CC BY-SA 4.0
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})
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
