Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RewriteRule htaccess if a file exists

I want to use htaccess to check if a file called offline.txt exists in the same directory as the htaccess file, if it exists then do:

RewriteRule ^.*$ /websiteOffline.php [L] 

and also have an exception to a certain range of ip addresses

The idea is that if i want to take my entire site down for maintanance i could simply place a file called offline.txt and that would do it and allow certain ip's to bypass this condition.

Any suggestions on how this can be acheived?

Thanks

i've tried the following code but doesnt seem to work:

RewriteEngine on
RewriteCond /offline.txt -f
RewriteRule  ^(.*)  /websiteOffline.php [L]

update

Just used Jon's suggestion as folows:

RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/offline.txt -f
RewriteRule  ^(.*)  /websiteOffline.php [L]

Slight problem with this is that the file websiteOffline.php is in the folder where the rewritecond is applied so hence is not able to display that file. any suggestions

like image 936
John Smith Avatar asked Sep 21 '25 04:09

John Smith


1 Answers

You can't use a relative location for the -f test. You'll need to include the full path:

RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/folder/offline.txt -f
RewriteCond %{REQUEST_URI} !/websiteOffline.php
RewriteCond %{REMOTE_ADDR} !^12\.34\.56\.78$
RewriteRule  ^(.*)  /websiteOffline.php [L]

where /folder/ is the path that your htaccess file is in.

Here, if your IP address is 12.34.56.78 and you try accessing the folder, it won't redirect you.

like image 178
Jon Lin Avatar answered Sep 23 '25 13:09

Jon Lin