site123
site123

Reputation: 41

Replace ?id= and .php from url via htaccess in php

I want to replace ?id= and .php with slash / in my post url.

I tried many answers from other questions but did not work for me like this one -

https://webmasters.stackexchange.com/questions/56411/remove-php-and-id-from-url-and-replace-with-slash/79438

Example Url - 
https://example.com/testing/events/news/post.php?id=13/Checking-to-see-if-this-works

I want this example url to be like this

https://example.com/testing/events/news/post/13/Checking-to-see-if-this-works

I used following htaccess code and it removes .php extension from url but can't figure out how to replace ?id= with /

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]

output -

https://example.com/testing/events/news/post?id=13/Checking-to-see-if-this-works

I still can't replace ?id= with /

Thanks for your help :)

Upvotes: 0

Views: 510

Answers (1)

anubhava
anubhava

Reputation: 785316

You may use these rules in your site root .htaccess:

Options -MultiViews
RewriteEngine On

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+(testing/events/news/post)\.php\?id=([^\s&]+) [NC]
RewriteRule ^ /%1/%2? [R=301,L,NE]

# internal forward from pretty URL to actual one
RewriteRule ^(post)/(.+)/?$ $1.php?id=$2 [L,QSA,NC]

# add .php extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

Upvotes: 1

Related Questions