【问题标题】:Setting site maintenance mode with php and .htaccess使用 php 和 .htaccess 设置站点维护模式
【发布时间】:2017-05-16 14:30:25
【问题描述】:

我正在尝试使用 php 和 .htaccess 文件启用/禁用站点维护模式。

我想找到一种方法来使用 PHP 注释/取消注释 .htaccess 文件中 # BEGIN/END MAINTENANCE MODE 之间的行。

# 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

有什么想法吗?

【问题讨论】:

  • 允许 PHP 修改 .htaccess 文件似乎是一个巨大的安全风险。
  • 您通过创建或删除(重命名)文件maintenance.html 来切换模式,而不是通过启用/禁用该规则集。
  • php 重命名很有用:php.net/manual/en/function.rename.php
  • 如何重命名?如果文件不存在,则会发生重定向,但我收到文件未找到消息...

标签: php apache .htaccess mod-rewrite url-rewriting


【解决方案1】:

正如其他人在 cmets 中提到的那样;您不希望 PHP 对您的 htaccess 文件具有写入权限。这可能存在安全风险。

作为@arkascha mentioned,一种方法是检查maintenance.html文件是否存在,并基于此启用/禁用维护模式:

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>

然后,在 PHP 方面,正是您想要创建注释/取消注释逻辑的位置,您只需重命名 maintenance.html 文件。像这样:

<?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');

还有一个注意事项;使用503码进行维护:
What is the correct HTTP status code to send when a site is down for maintenance?

【讨论】:

    猜你喜欢
    • 2016-01-10
    • 2013-09-19
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多