mod_rewrite: Redirect request to subdir with many subfolders of different structures + redirect to index.php

自作多情 提交于 2019-12-04 14:18:57

This should do it:

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 %{DOCUMENT_ROOT}/subdir%{REQUEST_URI} -f
RewriteRule ^ /subdir%{REQUEST_URI} [L]

RewriteRule ^ /index.php [L]

An update with a slight optimization.

RewriteEngine on
#RewriteBase /

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

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^[^/]+\.[^/]+$ - [NC,L]

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

RewriteRule ^ index.php [L]
  • The above will work with anydirectory/subdir

Change log:

  • RewriteBase commented for use of relative path.

  • Checking for /file.ext (or whether in current directory). the below will check whether file is present in current directory.

    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^[^/]+\.[^/]+$ - [NC,L]

  • RewriteCond %{DOCUMENT_ROOT}/subdir%{REQUEST_URI} -f

    captures current directory in %1 and the file.ext in %2

Why not simply use an Alias:

Alias /folder /subdir

And redirect to index.php in your 404 page? It has the advantage, 404 is still caught into the weblog.

Try adding the following to the .htaccess file in the root/folder directory of your site.

RewriteEngine on
RewriteBase /folder

#capture the Subfolder/file.xx
RewriteCond %{REQUEST_URI} ^/[^/]+/([^/]+)$
#if the subdir/subfolder/file.xx exists
RewriteCond %{DOCUMENT_ROOT}/subdir/%1 -f  
#Serve this file
RewriteRule ^ /subdir/%1 [L,S=1]
#else send to index.php in root directory  
RewriteRule ^  /index.php [L]  

I am assuming you want to send the request to the index.php in the root dir. If it is in the folder directory instead, change the last rule to

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