Question

I made a PHP framework that has a built in TPL system. It fetches the ending of the url, and finds the file that has that string. So if the url is http://website.com/tagHere the Tpl system would look for the file called tagHere.php. Everything works fine with it, but I'm now trying to expand the framework to have a built-in backend panel. I've tried multiple ways, but it just refuses to work.

I decided to take a look at Wordpress' htaccess, since they do exactly what I'm trying to accomplish. Here is how their htaccess works.

They check if the requested file name is a file. If it isn't a file, then they check if it is a folder. If it isn't a folder, they redirect to index.php. I want it to check if it's a file/folder, and if it isn't to remove the .php tag from the URL, so the TPL system can get the specified file and return it.

Here was my original .htaccess file.

RewriteRule ^(|/)$ index.php?url=$1
RewriteRule ^([a-zA-Z0-9_-]+)(|/)$ index.php?url=$1`

Here is Wordpress' original .htaccess file.

<ifmodule mod_rewrite.c="">
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</ifmodule>

Here was my attempt:

<ifmodule mod_rewrite.c="">
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . /index.php [L]
RewriteRule ^(|/)$ index.php?url=$1
RewriteRule ^([a-zA-Z0-9_-]+)(|/)$ index.php?url=$1
</ifmodule>

When I try the above htaccess, it returns a 404 error.

Was it helpful?

Solution

The Rule

RewriteRule . /index.php [L]

Will always match every URL because it says something like "if there is a character in the URL, then redirect".

What you're looking for is something like this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^admin/(.*?)$ admin.php?location=$1 [L]
RewriteRule ^(|/)$ index.php?url=$1
RewriteRule ^([a-zA-Z0-9_-]+)(|/)$ index.php?url=$1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top