You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.htaccess中重写JS文件?请求重定向至PHP脚本失败求助

解决.htaccess重定向静态文件到PHP脚本失效的问题

问题原因分析

你的两个方案失效的核心原因是:Apache会优先处理存在的静态文件请求,在mod_rewrite规则触发前就直接返回了test.js的内容,导致rewrite规则没有被执行。此外,原有规则还存在循环风险和匹配精度问题。

修正后的规则方案

方案1(优化版)

RewriteEngine On  
RewriteBase / 
# 仅处理初始请求,避免内部重定向循环
RewriteCond %{ENV:REDIRECT_STATUS} ^$
# 验证请求的文件确实存在
RewriteCond %{REQUEST_FILENAME} -f
# 精确匹配test.js请求(不区分大小写)
RewriteCond %{REQUEST_URI} /test\.js$ [NC]
# 重定向到处理脚本,传递请求的文件路径
RewriteRule ^ /handler.php?filename=%{REQUEST_URI} [L]

方案2(优化版)

RewriteEngine On  
RewriteBase / 
# 仅处理初始请求,避免循环
RewriteCond %{ENV:REDIRECT_STATUS} ^$
# 确保文件存在
RewriteCond %{REQUEST_FILENAME} -f
# 精确匹配以test.js结尾的路径(不区分大小写)
RewriteRule ^(.*/test\.js)$ /handler.php?filename=$1 [L,NC]

关键配置检查

  1. 启用mod_rewrite:确保Apache已加载mod_rewrite模块,Linux系统可通过a2enmod rewrite命令启用,Windows或其他系统需在httpd.conf中取消LoadModule rewrite_module modules/mod_rewrite.so的注释。
  2. 允许.htaccess生效:在Apache站点配置文件中,确保目标目录的Directory块设置了AllowOverride All,示例:
    <Directory "/var/www/html">
        AllowOverride All
        Require all granted
    </Directory>
    

PHP处理脚本示例(handler.php)

需在脚本中完成请求统计,并返回原静态文件内容,同时做好安全校验:

<?php
// 统计请求次数(此处用文件存储,可替换为数据库)
$countPath = __DIR__ . '/request_count.txt';
$count = file_exists($countPath) ? intval(file_get_contents($countPath)) : 0;
file_put_contents($countPath, ++$count);

// 安全校验:仅允许处理test.js请求
$targetFile = $_SERVER['DOCUMENT_ROOT'] . $_GET['filename'];
if (!file_exists($targetFile) || strpos($targetFile, 'test.js') === false) {
    http_response_code(404);
    exit('File not found');
}

// 设置正确的响应头,返回文件内容
header('Content-Type: application/javascript');
readfile($targetFile);
?>

内容的提问来源于stack exchange,提问作者Aleksandr Pomozov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 09:27:52