.htaccess rewrite wildcard folder paths from host
.htaccess files are extremely useful in many cases for users who either do not have root permissions or for users who simply aren't comfortable in making changes in their web server's configuration file. Trying to debug .htaccess not working isn't always the easiest thing to do, however, hopefully by checking the discuss below mentioned about htaccess, mod-rewrite, , , .htaccess common problems as well as the troubleshooting tips, you'll have a better grasp on what you may have to modify to get your .htaccess file running smoothly.Problem :My desired result is change a file to root / from a N number of paths.
For example: www.host.com/a/b/c/e/f/g/images/1.jpg, where A~G is not always given. Result: www.host.com/images/1.jpg.
This is what I have so far: www.host.com/a/images --> www.host.com/images using: RewriteRule ^a/images/$ images/$1 [L].
What I need is a wildcard in front of /images/ like this: RewriteRule ^*/images/$ images/$1 [L].
How can I do this correctly in .htaccess?
RewriteRule ^a/images/$ images/$1 [L]
There is no capturing group in the RewriteRule pattern, so the $1 backreference is always empty and will only rewrite the request from /a/images/ to /images/ (note the trailing slash).
To rewrite a request to any path depth then you simply need to establish that there is something (even just 1 character) in the URL-path before /images/ in the requested URL.
Taking the above points into consideration you could do something like the following:
RewriteRule ./(images/.*) $1 [L]
The $1 backreference contains everything that we want to rewrite the request to. ie. images/<anything>.
The above would internally rewrite a request for /a/b/c/e/f/g/images/<anything> to /images/<anything>.
This should do the trick: RewriteRule ^.+/images/$ images/$1 [L]
In regex, the .+ is a wildcard matching at least one character, so it will match
www.host.com/**a**/images and www.host.com/**a/b**/images but not www.host.com/images.
When working with regular expressions for pattern matching, I have always found this page helpful: http://regular-expressions.info/.
Comments
Post a Comment