匹配除静态资源之外的所有请求 - 除非它们是 `.php`

问题描述 投票:0回答:1

对于在 Apache Web 服务器上运行的 PHP 应用程序,我试图显示 503 维护页面:

RewriteRule ^.*$ /maintenance.html [R=503,L]
ErrorDocument 503 /maintenance.html

但是,静态资产(由 Apache 直接提供)应排除在外。当然可以加上

RewriteCond %{REQUEST_FILENAME} -f

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ /maintenance.html [R=503,L]
ErrorDocument 503 /maintenance.html

但是,这也将包括 PHP 入口点,因此仍可通过

https://example.com/index.php/foobar
访问 PHP 应用程序。

我似乎无法思考如何实现这一目标。即我想要

RewriteCond %{REQUEST_FILENAME} -f

匹配

.php
文件。

apache .htaccess mod-rewrite
1个回答
0
投票

您可以通过使用

RewriteCond
指令的组合来排除
.php
文件被重定向到维护页面来实现此目的。

以下是如何修改 Apache 配置来实现此目的:

# Set a flag when the request is for a PHP file
RewriteCond %{REQUEST_URI} \.php$
RewriteRule ^ - [E=PHP_REQUEST:1]

# Check if the request is for a static file that exists
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{ENV:PHP_REQUEST} !1
RewriteRule ^ - [L]

# If it's not a PHP file and not an existing static file, redirect to maintenance page
RewriteRule ^ /maintenance.html [R=503,L]

# Set the 503 ErrorDocument
ErrorDocument 503 /maintenance.html

  1. 第一个
    RewriteCond
    检查请求是否针对
    .php
    文件并设置 环境变量
    PHP_REQUEST
    更改为
    1
    (如果是)。
  2. 第二个
    RewriteCond
    检查请求是否针对现有静态文件
    (-f)
    并检查
    PHP_REQUEST
    不为 1。这可确保静态 如果文件存在并且 PHP 文件也被排除在重定向之外 排除。
  3. 如果请求不是针对现有静态文件并且不是 PHP 请求,则 将被重定向到维护页面。

我希望这会起作用......

#Apache-Age #mod-rewrite

© www.soinside.com 2019 - 2024. All rights reserved.