0

I'm new to htaccess and I want to know how can I do this two things and if they are recommended or if is there another better way to achieve a SEO friendly and nice URL:

  1. Redirect from www.example.com/products?id=car to example.com/car . If you can tell me the best method for SEO friendly it would be great (301 or whatever).
  2. Show always the url example.com/car as a pretty url and not with symbols, even when clicking a link that redirects to www.example.com/products?id=car.
anubhava
  • 761,203
  • 64
  • 569
  • 643

1 Answers1

1

You can use this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On
RewriteBase /example/

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} /products(?:\.php)?\?id=([^\s&]+) [NC]
RewriteRule ^ %1? [R=302,L,NE]

# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ products.php?id=$1 [L,QSA]
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thank you so much. Don't know what i'm doing wrong but it doesn't work. I type the url www.example.com/car and it shows that the web "product" doesn't exist. – Estirpicidades Jul 01 '15 at 10:47
  • I solved it, I didn't remember to put .php, right after products . Sorry I'm very noob. Anyways, when I type the URL /car it works properly, but when I navigate to products?id=car , the URL is products?id=car , not a pretty one. – Estirpicidades Jul 01 '15 at 10:51
  • Yes I'm using /products.php?id=car , that's what I get when I click on a link. I'm missing something there because I can't get the pretty URL. – Estirpicidades Jul 01 '15 at 11:24
  • Exact same rule redirects me from `http://localhost/products.php?id=car` to `http://localhost/car` on my Apache – anubhava Jul 01 '15 at 13:05
  • Im using RewriteBase /example/ because I'm working on directory localhost/example/ then I rewrite the external redirect like this RewriteRule ^example/%1? [R=302,L,NE] . The issue should be there. – Estirpicidades Jul 01 '15 at 17:14
  • 1
    Finally it is working! I really appreciate so much your help. One last question, is that good for SEO? – Estirpicidades Jul 02 '15 at 07:33
  • Another question, if I want to get another parameter from products like, http://localhost/products.php?id=car&color=red , what should I do? – Estirpicidades Jul 02 '15 at 08:29
  • Using same pattern you can expand these rules for 2 parameters. If you're stuck then open a new question and we'll answer. – anubhava Jul 02 '15 at 08:34
  • I opened this question http://stackoverflow.com/questions/31180314/seo-friendly-and-pretty-url-htaccess – Estirpicidades Jul 02 '15 at 09:12