Mod_rewrite if file exists

I already have two rewrite rules that work correctly, but another code needs to be added to work perfectly.

I have a website hosted on mydomain.com and all subdom.mydomain.com are rewritten to mydomain.com/subs/subdom. My CMS should handle the request, if the existing file does not exist, the rewriting is done as follows:

RewriteCond $1 !^subs/ RewriteCond %{HTTP_HOST} ^([^.]+)\.mydomain\.com$ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ subs/%1/index.php?page=$1 [L] 

My CMS handles the next part of the parsing as usual. The problem is that the file really exists, I need to link it without going through my CMS, I managed to do it as follows:

 RewriteCond $1 !^subs/ RewriteCond %{HTTP_HOST} ^([^.]+)\.mydomain\.com$ RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^(.*)$ subs/%1/$1 [L] 

So far it looks like a charm. Now I am picky, and I need to have the default files, which are stored in subs / default /. If the file exists in the subdomain folder, we must capture it, but if not, we need to get the file from the default subdomain. And if the file does not exist anywhere, we should use page 404 from the current subdomain, if not.

I hope this will be described fairly well. Thank you for your time!

+4
source share
2 answers

The problem is that you need to provide the full path to the file system in order to get -f and -d to work. If you are in the root directory of a document, you can use this rule:

 RewriteCond $1 !^subs/ RewriteCond %{DOCUMENT_ROOT}/subs/default/$1 -f [OR] RewriteCond %{DOCUMENT_ROOT}/subs/default/$1 -d RewriteRule ^(.*)$ subs/default/$1 [L] 

But if you are somewhere else, it will be difficult to get the prefix of the correct path.

+3
source

Thanks to Gumbo, I was able to figure out how to fix this. Here is what I came up with:

 #GET FILE FROM THE SUBDOMAIN DIRECTORY IF IT EXISTS RewriteCond $1 !^subs/ RewriteCond %{HTTP_HOST}%{REQUEST_URI} ^([^.]+)\.clan-websites\.com(.*)$ RewriteCond %{DOCUMENT_ROOT}/subs/%1/%2 -f [OR] RewriteCond %{DOCUMENT_ROOT}/subs/%1/%2 -d RewriteRule ^(.*)$ subs/%1%2 [L] #GET THE DEFAULT FILE IF NOT FOUND IN SUBDOMAIN RewriteCond $1 !^subs/ RewriteCond %{REQUEST_URI} ^(.*)$ RewriteCond %{DOCUMENT_ROOT}/subs/factory/%1 -f [OR] RewriteCond %{DOCUMENT_ROOT}/subs/factory/%1 -d RewriteRule ^(.*)$ subs/factory%1 [L] #SEND THE DATA TO THE SUBDOMAIN CMSMS SINCE NO FILE EXISTS RewriteCond $1 !^subs/ RewriteCond %{HTTP_HOST}%{REQUEST_URI} ^([^.]+)\.clan-websites\.com(.*)$ RewriteCond %{DOCUMENT_ROOT}/subs/%1/%2 !-f [OR] RewriteCond %{DOCUMENT_ROOT}/subs/%1/%2 !-d RewriteRule ^(.*)$ subs/%1/index.php?page=$1 [L] 
+1
source

Source: https://habr.com/ru/post/1308848/


All Articles