Trapp
Trapp

Reputation: 4349

Mod Rewrite (SEO Friendly URL's)

You'd think I'd easily be able to find the answer to this on S/O, but I've tried everything and after a few hours of frustration I'm giving in and seeing what the real experts think.

I'm "sure" this can be done with mod rewrite, but I'll defer to you.

Problem: I'm attempting to turn a URL like this...

http://domain.com/new-cars/state.php?stateCode=al

Into this at minimum...

 http://domain.com/new-cars/al-new-cars

Though, ideally I'd get it to look like this (yes, I'm willing to rewrite some code to use the full state name as the $stateCode variable to make it easier!)...

http://domain.com/new-cars/alabama-new-cars

Ultimately the plan is to be able to use URL's in links such as...

http://domain.com/new-cars/alabama-new-cars

And have .htaccess take car of associating this SEO-friendly URL with the dynamic version and displaying the page properly.

Either way, I haven't been able to figure out how to do this like I need.

Here's what I've tried.

 Options +FollowSymlinks

  RewriteEngine on
  RewriteBase /

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d

  RewriteRule ^new-cars/([^-]*)-new-cars/$ /new-cars/state.php?stateCode=$1 [L,QSA,NC]

And different variations that I've created using 2 different mod rewrite generators and various answers to other people's questions.

Absolutely nothing is working.

I expect when I go to

http://domain.com/new-cars/state.php?stateCode=AL

That it rewrites the URL to

http://domain.com/new-cars/AL-new-cars

...but it does not. Instead, it stays exactly the same dynamic URL I typed in. If I go to the "desired" rewrite URL I get a 404 error saying the page doesn't exist.

What am I doing wrong?

I thought maybe my .htaccess privileges weren't set right, but I can do a 301 redirect through .htaccess quite easily, so that's not it.

Maybe someone here can help. I've tried to so many permutations, even settling for the most basic rewrite just to see if I could get it to work - but nothing.

Any help is appreciated!

Upvotes: 0

Views: 127

Answers (1)

Croises
Croises

Reputation: 18671

You can use:

Options +FollowSymlinks

RewriteEngine on
RewriteBase /

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+new-cars/state\.php\?stateCode=([^\s&]+) [NC]
RewriteRule ^ /new-cars/%1-new-cars? [R=301,L,NE]

# internal forward from pretty URL to actual one
RewriteRule ^new-cars/([^-]*)-new-cars/?$ /new-cars/state.php?stateCode=$1 [L,QSA,NC]

Upvotes: 1

Related Questions