Home > Software engineering >  URL Rewriting Using .htaccess for PHP
URL Rewriting Using .htaccess for PHP

Time:12-03

I want to convert this url example.com/post.php?id=12345&title=xyz to example.com/12345/xyz

I am able to do example.com/12345 but I can't get /xyz

RewriteEngine On

RewriteRule ^post/([a-zA-Z0-9-/] )$ post.php?id=$1
RewriteRule ^post/([a-zA-Z-0-9-] )/ post.php?id=$1

CodePudding user response:

With your shown samples, please try following htaccess Rules. Please make sure to clear your browser cache before testing your URLs.

This solution assumes that you are hitting example.com/post.php?id=12345&title=xyz sample url in browser and want to change it to example.com/12345/xyz

##Enabling engine here.
RewriteEngine ON
##Extrenal redirect 301 to mentioned url by OP in question.
RewriteCond %{THE_REQUEST} \s/post\.php\?id=([^&]*)&title=(\S )\s [NC]
RewriteRule ^ %1/%2? [R=301,L]

##Internal rewrite to post.php with query strings.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)/?$ post.php?id=$1&title=$2 [QSA,L]
  • Related