0

I have a subdirectory called /i/ where I have images and videos saved. Files like png, gif, and mp4. I have some code in the .htaccess file to silently redirect from root to /i.

Example: domain.com/awE1.png is silently redirected to domain.com/i/awE1.png

Code:

RewriteCond %{REQUEST_URI} !/i/ [NC]
RewriteRule \.(?:jpe?g|gif|bmp|png|tiff|ico|mp4)$ i%{REQUEST_URI} [L,NC]

The problem is, if there is a file in the root folder, or another subdirectory such as /s and the file is an image, it will just result in a 404 error. Is there any way I can make .htaccess only look for the predefined file extenstions in the root folder?

Thanks!

1 Answer 1

1

You should not rewrite files existent under root or other directory, like this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/i/ [NC]
RewriteRule \.(?:jpe?g|gif|bmp|png|tiff|ico|mp4)$ i%{REQUEST_URI} [L,NC]

With the first RewriteCond, it rewrites only nonexistent image file, any file that exists in other directory is not rewrited to /i/ folder.

Sign up to request clarification or add additional context in comments.

2 Comments

This still (unnecessarily) checks requests that are outside the root folder. This could be optimized to check only root requests by modifying the regex... eg. ^[^/]+\.(?:jpe?g|gif....
OK Mr White, very nice. I'm grocer in the day, at the evening, I could take my old job: programmer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.