Redirect from one directory to another with mod_rewrite

匆匆过客 提交于 2019-12-19 07:11:08

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11273608/redirect-from-one-directory-to-another-with-mod-rewrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!