Tiaw Tiaw - 1 year ago 37
Ajax Question

Rewrite htacces can't find files

I made an ajax website that call php pages from /pages folder inside my

, so i made a rewrite in
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
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">
$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";

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

Answer Source

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.