I have a url like
localhost/index?id=2
How do I hide the id part by using htaccess and just show:
localhost/index/2
I have a url like
localhost/index?id=2
How do I hide the id part by using htaccess and just show:
localhost/index/2
In order to catch the query string, you need to use either %{QUERY_STRING}
or %{THE_REQUEST}
:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
# Redirect /index?id=2 to /index/2
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\?id=([^&\s]+) [NC]
RewriteRule ^ /index?%1 [R=302,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [QSA,L]
Given that you don't have other rules that may conflict with your needs, this should work just fine.
Once you confirm its working you can change from 302
, to 301
but in order to avoid caching, tests should be always done using 302
.
Another way using %{THE_REQUEST}
would be like this:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
# Redirect /index?id=2 to /index/2
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\?id=([^&\s]+) [NC]
RewriteRule ^ /index/%1? [R=302,L]
# Internally forward /index/2 to /index.php?id=2
RewriteRule ^index/([0-9]+)/?$ /index.php?id=$1 [QSA,NC,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [QSA,L]
RewriteEngine On
RewriteRule ^([A-Za-z0-9-+_%*?]+)/?$ index.php?id=$1 [L]
([A-Za-z0-9-+_%*?]+) <-- this part with in the brackets is used as regular expression means you are looking for any Character from A to z and from a to z and any number from 0 to 9 and symbol - , +,_,%,*,? and the + sign after the closing square bracket means more than one .
In short You are asking to for which is ([in here]+) and it's more than one ,if however you remove the + symbol after the bracket it'll return only the first character