Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

.htaccess - mod_rewrite if file exists

I already have two rewrite rules that work correctly for now but some more code has to be added to work perfectly.

I have a website hosted at mydomain.com and all subdom.mydomain.com are rewrited to mydomain.com/subs/subdom . My CMS has to handle the request if the file being reached does not exist, the rewrite is done like so:

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 if a file really exists, I need to link to it without passing through my CMS, I managed to do it like this:

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 seems to work like a charm. Now I am being picky and I need to have default files that are stored in subs/default/. If the file exists in the subdomain folder, we should grab this one but if not, we need to get the file from the default subdomain. And if the file does not exist anywhere, we should be using the 404 page from the current subdomain unless there is none.

I hope it describes well enough. Thank you for your time!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that you need to provide the absolute file system path to get -f and -d working. If you’re in the document root, 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’re somewhere else, it’s going to be hard to get the right path prefix.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...