views:

28

answers:

2

So I have a webpage that queries some data based on this parameter search.php?state=AL.

What I'm trying to do is write a rule in my .htaccess file that will:

  1. translate website.com/state/AL into search.php?state=AL
  2. If a user specifically request search.php?state=AL then translate that into /state/AL

I accomplished step 1 using this:

RewriteRule ^state/([A-Za-z][A-Za-z]) /search.php?state=$1 [NC]

How can I accomplish step 2? I know I will have to use [R, NC] to actually rewrite the URL, but thats where I'm stuck.

EDIT: Not sure if this matters but my webhost forces me form some reason to add RewriteBase / to the top of my .htaccess file.

A: 

Something like this would do the trick:

RewriteRule ^state/([A-Za-z][A-Za-z]) /search.php?state=$1 [NC, L]
RewriteCond %{QUERY_STRING} state=([A-Za-z][A-Za-z])
RewriteRule ^search\.php$ /state/%1 [R=303, NC]
You
When I tried this one it gave me an Internal Server Error: `500`
Bob Dylan
+2  A: 

You want to perform the redirection only in the case that the original request was pointed to the /search.php?state= URL, like so:

RewriteEngine On

# Externally redirect /search.php?state=XX --> /state/XX
RewriteCond %{THE_REQUEST} ^[A-Z]+\s/search\.php\?state=([A-Z]{2}) [NC]
RewriteRule ^ http://%{HTTP_HOST}/state/%1? [R=301,L]

# Internally redirect /state/XX --> /search.php?state=XX
RewriteRule ^state/([A-Z]{2}) /search.php?state=$1 [NC]
Tim Stone
Thats exactly what I wanted, but for some reason it's not working. It still shows `search.php?state=AL` in the address bar.
Bob Dylan
@Bob Dylan - Yeah, that's because I stupidly forgot to escape the question mark. I'll edit the answer. (And I forgot to kill the query string on the redirect, I added that in too)
Tim Stone
@Tim: Thanks that fixed it!
Bob Dylan