Home > front end >  Load image based on folder and ignore further text after trailing slash
Load image based on folder and ignore further text after trailing slash

Time:06-03

I have a folder structure like

root/images/folder1

In folder1 is exactly 1 image for example test.jpg

Now I would like to show the image test.jpg only by calling the URL

www.example.com/images/folder1

Is it possible to define mod_rewrite in a way to only match the folder name and therefore load the image inside.

In case the user would call

www.example.com/images/folder1/somethingelse

I would still like to call the image taking only into account what is between the two "/" after www.example.com/images

CodePudding user response:

I think what you are looking for is a single internal rewrite that matches exactly that path prefix:

RewriteEngine on
RewriteRule ^/?images/folder1 /images/folder1/test.jpg [END]

UPDATE:

In the first comment to this question you now additionally ask whether it is possible to implement a more generic rule:

RewriteEngine on
RewriteRule ^/?images/([^/] ) /images/$1/test.jpg [END]

CodePudding user response:

I don't have to avoid the trailing slash. I would be also happy with www.example.com/images/folder1/

In that case, you would just use the DirectoryIndex directive, either in the specific folder to apply to just that folder or in the parent folder (ie. /images) to apply to all subfolders.

The DirectoryIndex directive instructs Apache/mod_dir which file to serve when requesting the directory. Normally, this is set to index.html (default) or index.php etc. But it can be set to anything.

For example:

# /images/.images
DirectoryIndex test.jpg

The above would tell mod_dir to try and serve test.jpg from any (sub)directory when requesting the directory itself.

For example, requesting /images/folder1/ would serve /images/folder1/test.jpg if it exists, otherwise a 403 Forbidden is served (assuming mod_autoindex is enabled, but directory listings are disabled).

If you omit the trailing slash on the directory then mod_dir will first trigger a 301 redirect to append the trailing slash (in order to "fix" the URL).

This of course assumes you are always serving test.jpg from whatever directory is requested.


In case the user would call

www.example.com/images/folder1/somethingelse

I would still like to call the image taking only into account what is between the two "/" after www.example.com/images

This would potentially cause a duplicate content issue and have a negative effect on SEO. Not to mention opening your site up to abuse, eg. /image/folder1/malicious-keywords-here.

With the DirectoryIndex method discussed above then /images/folder1/somethingelse would naturally result in 404 (unless a file by that name existed).

If you wanted /images/folder1/somethingelse to serve /images/folder1/ then you should implement an external 301 redirect to the canonical URL.

  • Related