能否用%{HTTP_HOST}与RewriteCond拦截网站?特定时段拦截配置求助
Hey there! Let's work through your time-based site blocking issue with Apache's mod_rewrite, and also cover some alternative methods that might be a better fit for your needs.
First, let's fix your existing setup. There are a few small tweaks needed to make it reliable:
- Server Timezone Check: The
%{TIME_HOUR}variable uses your server's system timezone, not your local time. Double-check that the 11-15 hour range aligns with when you want the block to activate on the server's clock. - Escaped Domain Dots: In regex, dots match any character—so we need to escape them in
www.facebook.comto ensure we're targeting the exact domain. - Cleaner Hour Range: Instead of listing each hour individually, we can use range conditions for better maintainability.
- Explicit Redirect Type: Adding
R=302tells browsers it's a temporary redirect (useR=403if you prefer returning a "Forbidden" error instead of sending users to a custom page).
Here's the revised working configuration:
<IfModule rewrite_module> RewriteEngine On # Block www.facebook.com between 11:00 and 15:59 server time RewriteCond %{HTTP_HOST} ^www\.facebook\.com$ [NC] RewriteCond %{TIME_HOUR} >=11 RewriteCond %{TIME_HOUR} <=15 RewriteRule ^(.*)$ /restriction_social.html [L,R=302] </IfModule>
If mod_rewrite feels overly complex, these approaches might suit you better:
1. Apache 2.4+ mod_authz_core (More Readable)
This module lets you define access controls with straightforward time-based logic, no rewrite rules required:
<If "%{HTTP_HOST} == 'www.facebook.com' && %{TIME_HOUR} >= 11 && %{TIME_HOUR} <= 15"> # Redirect to your custom restriction page Redirect 302 / /restriction_social.html # OR, if you want to block access entirely with a 403 error: # Require all denied </If>
2. Server-Side Script for Advanced Logic
If you need flexibility (like different rules for weekdays vs weekends), a simple server-side script can handle dynamic checks. For example, with PHP:
First, update your Apache config to route requests to the script:
<IfModule rewrite_module> RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.facebook\.com$ [NC] RewriteRule ^(.*)$ /time_block_check.php [L] </IfModule>
Then create time_block_check.php in your document root:
<?php $currentHour = (int)date('H'); $currentHost = $_SERVER['HTTP_HOST']; // Check if we're in the blocked window for the target domain if ($currentHost === 'www.facebook.com' && $currentHour >= 11 && $currentHour <= 15) { header('Location: /restriction_social.html'); exit; } else { // Allow normal access to the site header("Location: https://$currentHost{$_SERVER['REQUEST_URI']}"); exit; } ?>
内容的提问来源于stack exchange,提问作者Eduardo Hernández

