Redirect to photo using htaccess

I mainly use htaccess. I have a hidden directory that I would prefer not to use, and I need shorter links:

I would like to

http://example.com/12940.png 

go over

 http://example.com/_images/12940.png 

Here is my rule:

 RewriteRule ^([A-Za-z0-9\_\-\/]+).([A-Za-z]+)$ "_images/$1.$2" 

What's wrong with this, I get 500.

+4
source share
2 answers

Here is what you need to do:

 RewriteEngine On RewriteRule ^([a-z0-9_\-]+)\.([az]+)$ _images/$1.$2 [NC,L] 

using NC (case insensitive) you do not need to set A-Za-Z, and L means the last rule if after that you have other rules.

+3
source

This rule fails because it has / . Thus, the redirected URL ( _images/12940.png ) falls into the rule again, and mod_rewrite tries to redirect it ( _images/_images/12940.png ).

So you should check if the allready path starts with _images :

 RewriteRule ^(?!_images)([A-Za-z0-9\_\-\/]+).([A-Za-z]+)$ "_images/$1.$2" 

You can also improve your rule as follows:

 RewriteRule ^(?!_images)([a-z0-9_\-/]+\.[az]+)$ _images/$1 [NC] 

There is no need to avoid _ and / , but you must avoid . because it matches any character otherwise. NC makes the rule case insensitive, so you do not need additional AZ .

0
source

Source: https://habr.com/ru/post/1381862/


All Articles