1

I'm trying to enable/disable site maintenance mode with php and the .htaccess file.

I would like to find a way to comment/uncomment the lines between # BEGIN/END MAINTENANCE MODE in the .htaccess file with PHP.

# BEGIN MAINTENANCE MODE
# <IfModule mod_rewrite.c>
#  RewriteEngine on
#  RewriteCond %{REMOTE_ADDR} !^111\.111\.111\.111
#  RewriteCond %{REQUEST_URI} !maintenance.html$ [NC]
#  RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif) [NC] 
#  RewriteRule .* maintenance.html [R=302,L]
# </IfModule>
# END MAINTENANCE MODE

Any ideas?

sepehr
  • 17,110
  • 7
  • 81
  • 119
mlattari
  • 135
  • 2
  • 10

1 Answers1

2

As others mentioned in the comments; you don't want PHP to have write access to your htaccess file. That could be a security risk.

As @arkascha mentioned, one approach could be to check if the maintenance.html file exists or not and enable/disable the maintenance mode based on that:

Options +FollowSymLinks

<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteCond %{REMOTE_ADDR} !^111\.111\.111\.111
    RewriteCond %{REQUEST_URI} !maintenance.html$ [NC]
    RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif) [NC]

    # Check if the maintenance.html file exists,
    # if so, redirect all requests to that file.
    RewriteCond %{DOCUMENT_ROOT}/maintenance.html -f
    RewriteRule .* /maintenance.html [R=503,L]
</IfModule>

Then, on the PHP side of things, exactly where you wanted to create that comment/uncomment logic, you just rename the maintenance.html file. Something like this:

<?php
# Assuming you're in the document root...

# Disables maintenance mode
rename('maintenance.html', 'maintenance.html.bak');

# Enables maintenance mode
rename('maintenance.html.bak', 'maintenance.html');

One more note; Use 503 code for maintenance:
What is the correct HTTP status code to send when a site is down for maintenance?

sepehr
  • 17,110
  • 7
  • 81
  • 119