Search code examples
php.htaccessurl-rewritingget

hiding get variable in url


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

Solution

  • 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]