大网数据广告活动
网站运营与故障问答

Rewritting .htaccess file to direct to files using a wildcard

· 52CE 我爱测

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 lo…

问题原文

原帖链接 · 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 A12 format, 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})

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2019-02-26)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。