Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite URLs in .htaccess for replacing Query parameters with forward slash (id?=value)

I have made sure that rewrite engine is enabled and removing .php extensions is working so I know that isn't the issue.

what I'm trying to do is simply remove the ?id=value aspect of the URL, so basically making the URL look like such:

folder/medias/value

Instead of

folder/medias?id=value

My current .htaccess looks like this:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

RewriteRule ^404/?$ /404.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^ 404.php [L,R]
like image 926
Rajat Singh Avatar asked Oct 21 '25 05:10

Rajat Singh


2 Answers

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

RewriteEngine ON
##Rules for external rewrite.
RewriteCond %{THE_REQUEST} \s/([^.]*)\.php\?id=(\S+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]
##Rule for internal rewrite.
RewriteRule ^([^/]*)/([^/]*)/?$ $1?id=$3 [L]
like image 182
RavinderSingh13 Avatar answered Oct 24 '25 02:10

RavinderSingh13


You may try this code inside the /folder/.htaccess (create this file if it doesn't exist):

RewriteEngine On

# External redirect from /folder/media?id=val to /folder/media/val
RewriteCond %{THE_REQUEST} /(\S+?)\.php\?id=([^&\s]+)\s [NC]
RewriteRule ^ /folder/%1/%2? [R=301,L,NE]

# Internal rewrite from /folder/media/val to /folder/media?id=val
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/([\w-]+)/?$ $1.php?id=$2 [L,QSA]
  • Trailing ? in first rule is to remove query string from original URL.
  • %{REQUEST_FILENAME} !-f and %{REQUEST_FILENAME} !-d is to skip existing files and directories from rewrite in 2nd rule.
like image 44
anubhava Avatar answered Oct 24 '25 04:10

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!