Issue on htaccess

Hi guys.

I’m trying to create some pretty urls for my project, and I’m creating it with an .htaccess file.
I have to files which are page.php and post.php. Each one of them are being requested from diferent functions.
This is my .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)$ $1.php [L]
RewriteRule ^([^.]+)$ page.php?slug=$1

I want to set now for the post.php the same i use on page.php like:

RewriteRule ^([^.]+)$ post.php?slug=$1

But if i set it after the page.php, only works the first rule. If set change places, and set the post.php before the page.php, it only works the post.php.
Can someone help me on this?

Best regards.

You are creating a duplicate rule, ^([^.]+)$, and sending it to three different pages. What is your intention with this? Are you trying to make it load $1.php, page.php, and post.php, for every request? Apache can only route a single request to a single PHP file.

The correct way to do something like this is to use subdirectories (also: with [L], the first matching rule will be executed, subsequent matches will be ignored, so the $1.php rule should go at the bottom).

RewriteRule ^page/([^.]+)$ page.php?slug=$1 [L]
RewriteRule ^post/([^.]+)$ post.php?slug=$1 [L]
RewriteRule ^([^.]+)$ $1.php [L]

Result:

example.com/page/about-us --> page.php?slug=about-us
example.com/post/hello-world --> post.php?slug=hello-world
example.com/contact --> contact.php

If you’re trying to recreate a system like WordPress, whereby pages can use any hyperlink and don’t require a specific subdirectory like “page/” or “post/”, then you need only one rule, as shown below, and the logic to determine if it’s a post or page goes in the index.php file.

RewriteRule ^([^.]+)$ index.php [L]
1 Like

Hi @baileyherbert.
Thank you so much for your help on this, but unfortunately it didn’t work.
I would really like to use it like a WordPress system, where there is no other subdirectories involved.
I use 2 different files that call make the requests and are used like Wordpress template files.
The true is that if i use the first htaccess rules, the css will be corrupted because folders are added to URL, and that is not what I want.
So i probably need to make some adjustments on those files.
I read about this on some website but didn’t manage to have it fixed.
But thank you so much for your help on this. You were really helpfull with the explanation!

Best regards.