doubi4435 2016-08-03 08:49
浏览 26
已采纳

重写htaccess无法找到文件

I made an ajax website that call php pages from /pages folder inside my index.php, so i made a rewrite in htaccess for return all my pages in my index so the ajax working well but when clicking refresh the page button or on first load, the function can't find files, return 404.php page all the time:

This is my htaccess:

Options +FollowSymLinks

RewriteEngine On

RewriteBase /
RewriteRule ^([a-zA-Z0-9\-]*).php$ index.php?p=$1 [L]

And this is my php function calling my pages:

<div id="ajax-container">
<?php
 $d = "pages/";
 if (isset($_GET['p'])) {
    $p = strtolower($_GET['p']);
    if (preg_match("/^[a-z0-9\-]+$/", $p) && file_exists($d . $p . ".php")) {
        include $d . $p . ".php";
    } else {
        include $d . "404.php";
    }
 } else {
    include $d . "home.php";
 }
?>
</div>

I think the problem come from my rewrite because it's rewrite all pages php so I think it's also rewriting my index.php and so the function can't find the ['p'] but I'm not sure and I don't know if it's this how can I rewrite only files from my /pages folder

  • 写回答

1条回答 默认 最新

  • duanguangsong2380 2016-08-03 09:24
    关注

    index.php is getting picked up by your Rewrite on the second pass and being sent to index.php?p=index which doesn't have a corresponding page in your pages directory and so fetches 404.php.

    The normal way to avoid this is to add conditions for not file and not directory into your .htaccess (thus preventing URLs to files or directories that actually exist from being rewritten).

    You can do that by simply changing your .htaccess to:

    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([a-zA-Z0-9\-]+)\.php$ index.php?p=$1 [L]
    


    See Apache's RewriteCond manual.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)