php 使用 htaccess mod_rewrite 检查 file_exists() 是否存在

标签 php apache .htaccess redirect mod-rewrite

我正在使用 htacces mod_rewrite 重写我的网站 URL,例如:

/dir/file.php
/dir/file_example.php
/dir/file2.php?id=test

成为

/dir/file
/dir/file-example
/dir/file2-test

一切都好。现在我有一个 PHP 脚本来执行某些重定向,但在重定向之前我想检查文件(或 url)是否存在:

if(file_exists("/dir/file2-test")){ // redirect on page
}else{ // redirect on index

但是 file_exists() 在这种情况下返回 false。

还有另一种方法可以通过 php 检查这些页面/url(file2-test、file-example 等)是否存在?

PS:由于 htaccess 规则的复杂性,我无法在末尾附加“.php”。

最佳答案

可以通过实际调用来检查该 URL 是否确实存在,但代价是执行真正的 http 请求,并产生由此导致的所有服务器负载和延迟。

$file = 'http://www.domain.com/dir/file2-test';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}

来源:http://www.php.net/manual/en/function.file-exists.php#75064

我根本不推荐这个。

我没有看到任何真正的机会从 php 探测 RewriteEngine 逻辑,因此我建议将整个重写逻辑集成到 htaccess 或 php 中。

关于php 使用 htaccess mod_rewrite 检查 file_exists() 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35457911/

相关文章:

apache - RewriteCond %{SERVER_NAME} 语法

PHP - 获取在第二个函数插入语句中使用的最后语句 PK ID

php - Dompdf 远程图像未以 pdf 格式显示

php - .htaccess for apache 2.2 不适用于 apache 2.4 vagrant development box

php - 保存 $_GET 变量时遇到问题

php - 以编程方式将 ip 地址从 mysql 表添加到 .htaccess 文件并阻止用户

php - PHP实现的机票预订系统

php - 在网上商店快速结帐后,我如何进入 Paypal 确认付款? PHP

apache - 在 DV SSL 的 BEAST 攻击预防方面需要帮助

php - 如何使用brew安装的php?