Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect from one directory to another with mod_rewrite

The following is my directory structures:

admin\
controls\
images\
media\
lib\
models\
views\
index.php
.htaccess

The following is my .htaccess

RewriteEngine On 
RewriteRule /admin/images/(.*) /images/$1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php

I want everything in /admin/images be equal to /images in root directory. For example: http://www.example.com/admin/images/example.png will be the same as http://www.example.com/images/example.png

Problem with my .htaccess is: It goes to index.php instead of mirroring admin/images to images/


Solution

RewriteEngine On 
RewriteRule /admin/images/(.*) /images/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php
like image 406
invisal Avatar asked Jun 30 '12 11:06

invisal


2 Answers

You need to specify that your image rewrite rule is the last one in the row in order to prevent further rewriting. For that you simply specify [L] at the end of your image rewrite rule.

RewriteEngine On 
RewriteRule /admin/images/(.*) /images/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php

EDIT: Here is an explanation why the problem occurs (taken from the comments section in order to provide clarification).

You see the original %{REQUEST_FILENAME} will never change no matter how many stages of rewriting are performed. That means that when the second rule is reached that variable will actually still point to the existing image (which is in /admin/images/) rather to the one being rewritten and non-existing (/images/). That's the reason why the second rule will always be applied and why the two conditional lines from the example are almost always the first ones to be used during rewriting.

like image 137
brezanac Avatar answered Sep 28 '22 07:09

brezanac


Change the rule as follow:

RewriteEngine On 
RewriteRule ^admin/images/(.*) images/$1

And put your .htaccess in your document root, or however in the '/admin' parent folder.

like image 42
Zagorax Avatar answered Sep 28 '22 07:09

Zagorax