Mod_rewrite: If the file exists in another directory,

I have a website at example.com/test/ . Let's say the site is hosted as such:

 example.com └── test/  ├── assets/ │ └─ stylesheet.css │ ├── .htaccess └── index.php 

index.php Here is a router, as it is, for example, great to do now.

Whenever a user requests a page like example.com/test/stylesheet.css , I want to check if this file has assets/ , and if so, specify this file instead of specifying the index.php url index.php . Ideally, the following will work:

 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond assets/%{REQUEST_FILENAME} -f RewriteRule ^(.+)$ assets/$1 

But since %{REQUEST_FILENAME} is an absolute path, assets/%{REQUEST_FILENAME} turns out to be something like assets/home/public/test/stylesheet.css . %{REQUEST_URI} no better: it turns into assets/test/stylesheet.css . I also considered this question , but the answer did not work either.

Is there a way, without resorting to PHP, to do this? (If not, I just use the PHP readfile , but I don't want to worry about LFI or anything else.)

+8
.htaccess mod-rewrite
source share
1 answer

Try using the %{DOCUMENT_ROOT} and %{REQUEST_URI} vars

 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{DOCUMENT_ROOT}/assets/%{REQUEST_URI} -f RewriteRule ^(.+)$ assets/$1 

EDIT: I see, try this instead:

 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} ^/([^/]+)/(.+)$ RewriteCond %{DOCUMENT_ROOT}/%1/assets/%2 -f RewriteRule ^(.*)$ /%1/assets/%2 [L,R] 
+9
source share

All Articles