mod_rewrite: How to search in local folder, subfol

2019-04-16 01:28发布

I need to create the following rule to place in my .htaccess

  1. Firstly I want to execetue file in the main folder (/) (if requestedfile exists)
  2. Secondly I'd like to search for this file in subfolder -> /subfolder
  3. 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

2条回答
够拽才男人
2楼-- · 2019-04-16 01:43

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]
查看更多
一夜七次
3楼-- · 2019-04-16 01:49

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] 
查看更多
登录 后发表回答