Skip to content
Advertisement

Changing URL so post/{number} in HTML resolves post?id={number}, but still displays post/{number} as URL

I’m struggling pretty hard with .htaccess. Even though I looked up quite a few solutions here, I couldn’t get to setup the following:

I have a file called index.php. Inside the index.php I have a link like

<a href="post/12345678901">Post</a>

Clicking the link, should lead to a file in the same directory called post.php. Inside the post.php I’m grabbing the id through $GET[‘id’].

But I still like to display post/12345678901 as the URL.

I already tried editing the .htaccess but clicking the links leads to a 404.

Options +FollowSymlinks
RewriteEngine on

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

Advertisement

Answer

You have a RewriteRule but you probably need a ReWriteCondition to go with it else this rewrite will be applied to every call to a page on the apache.

Options +FollowSymlinks
RewriteEngine on

# Not a file
RewriteCond %{REQUEST_FILENAME} !-f
# not a directory
RewriteCond %{REQUEST_FILENAME} !-d 

# Edited to show root location of files. 
# also added NoCaseSensitivity flag.
RewriteRule ^post/([0-9]+)/? /post.php?id=$1 [NC]

Also remove the first / in the second part of the RewriteRule because that will be domain.com/post.php which might not be your actual file location.

Your HTML appears to be showing relative filepathing which is not a good idea and might come back to bite you in the future, As a recommendation every URL on the same domain on your HTML should start with a / so;

<a href="/post/12345678901">Post</a>

Which can then be manipulated by the .htaccess to go where you need, even in another folder (not the base).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement