I need to create the following rule to place in my .htaccess
- Firstly I want to execetue file in the main folder (/) (if requestedfile exists)
- Secondly I'd like to search for this file in subfolder -> /subfolder
- And If the file doesn't exist in point 1 and 2 id like to redirect the request do /index.php
What would be the best way to do it.
Thanks for help :)
ps The first point could be eliminated as a simpler solution. So if the user entered url /file.jpeg the server would serach for this file in /subfolder and if didn't find this file than it would redirect the rquest do index.php
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]