DaFoot
DaFoot

Reputation: 1567

How do I use htaccess to remove ugly GET params?

I have a PHP website site that uses GET variables to determine what it should be doing...

eg /index.php?s=about&p=2

It seems that I should be able to change this using rewrite rules so I could use URLs like:

/about/2

How can I get that behaviour?

Upvotes: 0

Views: 58

Answers (1)

Jon Lin
Jon Lin

Reputation: 143906

  1. You need to change all of your links to look like /about/2.
  2. You need to adjust any relative links to be either absolute links or add this to the header of all your pages:

    <base href="/">
    
  3. Add these rules to the htaccess file in your document root to change the nice looking links back to the ugly links:

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)/([^/]+)/? /index.php?s=$1&p=$2 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)/? /index.php?s=$1 [L]
    
  4. Just so search engines can re-index your pages, you need to 301 redirect the old ugly ones to the nice looking ones by adding this to the same htaccess file:

    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?s=([^&]+)&p=([^&]+)
    RewriteRule ^index.php$ /%1/%2 [L,R=301]
    
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?s=([^&]+)
    RewriteRule ^index.php$ /%1 [L,R=301]
    

Upvotes: 1

Related Questions