Search code examples
apache.htaccessmod-rewriteurl-rewritingapache2

Apache2, mod_rewrite - use variable from prev condition in next condition


I would like to check if file exist in subdirectory. And I mean subdirectory that "is taken" from "subdomain".

Eg. url: "test.domain.com/file.txt" file location is "/test/file.txt"

I have wildacrd and i can't hardcode "test" directory. How can i do it?

I tried add %{DOCUMENT_ROOT}%1/$1 but this dosen't work.

Options +FollowSymLinks -MultiViews

RewriteEngine On

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain.com
RewriteCond %{DOCUMENT_ROOT}%1/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}%1/$1 -d
RewriteRule ^ /%1%{REQUEST_URI} [L]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain.com
RewriteRule ^images/(.*)$ /%1/image.php?test=$1 [L]

Solution

  • With your shown samples, please try following. Please make sure to clear your browser cache before testing your URLs.

    Options +FollowSymLinks -MultiViews
    RewriteEngine ON
    
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTP_HOST} ^([^.]+)\.domain.com [NC]
    RewriteCond %{DOCUMENT_ROOT}/%1/$1 -f [OR]
    RewriteCond %{DOCUMENT_ROOT}/%1/$1 -d
    RewriteRule ^(.*)/?$ %1/$1 [L]
    
    RewriteCond %{HTTP_HOST} !^www\.  [NC]
    RewriteCond %{HTTP_HOST} ^([^.]+)\.domain.com [NC]
    RewriteRule ^images/(.*)/?$ %1/image.php?test=$1 [QSA,NC,L]
    

    Fixes in OP's attempts: You need not to use condition RewriteCond %{ENV:REDIRECT_STATUS} ^$ in 2nd Rules sets, even first one may not need it but for safer side you can have it. Then your sequence of accessing path from %{DOCUMENT_ROOT} was not correct which was corrected here.