Redirecting from one directory to another using mod_rewrite

The following directory structures are listed:

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

Below 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 to be equal to / images in the root directory. For example: http://www.example.com/admin/images/example.png will be the same as http://www.example.com/images/example.png

The problem with my .htaccess: It accesses index.php instead of mirroring admin / images to images /


Decision

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

You need to indicate that the image rewrite rule is the last in the line to prevent further rewriting. To do this, you simply indicate [L] at the end of the 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 of why the problem occurs (taken from the comments section to provide clarification).

You see that the original %{REQUEST_FILENAME} will never change no matter how many rewriting stages it takes. This means that when the second rule is reached, this variable will still point to the existing image (which is located in /admin/images/ ), and not to the rewritten and non-existing one ( /images/ ). This is the reason why the second rule always applies and why the two conditional lines from the example are almost always the first ones to be used for rewriting.

+10
source

Change the rule as follows:

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

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

+4
source

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


All Articles