mod_rewrite: How to search in local folder, subfolder and then redirect to index.php

十年热恋 提交于 2019-12-04 19:33:47

I am assuming your URL looks like this: somesite.com/subfolder/file.extension. If URL is different give details.
Add this to your .htaccess in your DocumentRoot.

Options +FollowSymLinks -MultiViews -Indexes

RewriteEngine on
RewriteBase /

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

RewriteCond %{REQUEST_URI} ^/([\w]+)/([\w]+\.[\w]+)$ [NC]
RewriteCond %{DOCUMENT_ROOT}/%2 -f 
RewriteRule ^ /%2 [NC,L] 

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^ /index.php [L]

Changed to suit OPs requirement.

RewriteEngine on
RewriteBase /

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

RewriteCond %{REQUEST_URI} ([\w]+\.[\w]+)$ [NC]
RewriteCond %{DOCUMENT_ROOT}/%1 -f 
RewriteRule ^ /%1 [NC,L] 

RewriteCond %{REQUEST_URI} ([\w]+\.[\w]+)$ [NC]
RewriteCond %{DOCUMENT_ROOT}/subdir/%1 -f
RewriteRule ^ /subdir/%1 [L]

RewriteRule ^ /index.php [L]

This is just a supplemental to the approach ThinkingMonkey outlines. As I commented, the % variables are only available on the next cond or rule. However the rule $ variables are available for both the conds and the rule replacement string, hence rule 2 should be written as (with the same caveats about using DOCUMENT_ROOT):

RewriteCond %{DOCUMENT_ROOT}/$1 -f 
RewriteRule \w+/(\w+\.\w+)$ $1 [NC,L] 

or if you want to do the opposite

RewriteCond %{DOCUMENT_ROOT}/subdir/$1 -f 
RewriteRule (\w+\.\w+)$ subdir/$1 [NC,L] 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!