Jeff Walden
Jeff Walden

Reputation: 321

Regex for Rewriting Old URL in .htaccess

I'm not sure what the rewrite rule in my .htaccess needs to look like. My goal is to support old URL's that have parameters in them and convert them to the new URL.

Old URL

http://site1.domain.com/product.php?ID=12357/$10-gift-certificate

New URL

http://site1.domain.com/item/12357/$10-gift-certificate

The URL has various variables in it:

  1. Subdomain (site1)
  2. Item/Product ID (12357)
  3. Description ($10-gift-certificate)

So put another way, the architecture of the updated url looks like this:

http://[subdomain].domain.com/item/[ID]/[description]

Thanks for any suggestions!

Upvotes: 1

Views: 51

Answers (2)

Amit Verma
Amit Verma

Reputation: 41249

Try this rule :

RewriteEngine on
RewriteCond %{HTTP_HOST} ^sub.domain.com$ [NC]
RewriteCond %{THE_REQUEST} /product\.php\?id=([^/]+)/([^\s]+) [NC]
RewriteRule ^ item/%1/%2? [NE,NC,R,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^item/([^/]+)/([^/]+)/?$ product.php?id=$1/$2 [QSA,NC,L]

Upvotes: 1

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

Instead of supporting the old one you really are supporting the new ones like this

 RewriteRule  /?category/([^/d]+)/?$ index.php?category=$1 [L,QSA]

Where your new url would be ( what the user sees )

yoursite.com/category/1

Which would map to ( what the server sees )

index.php?category=$1

Old urls would work fine, as such. The user ( end client ) would see only the url you have links for on your webisite ( the new format I assume ), And because these are not redirects the url will not change in the browser.

So in your example

 http://[subdomain].domain.com/item/[ID]/[description]

You'd want something like this

RewriteRule  /?item/([\d]+)/([^/]+)/?$ product.php?ID=$1&description=$2 [L,QSA]

So this would be

INPUT

 http://site1.domain.com/item/12357/$10-gift-certificate

OUTPUT

 http://site1.domain.com/product.php?ID=12357&description=$10-gift-certificate 

-note- that the browser will not [R] redirect so the url will not change to output only the server sees it this way.

unless ID=12357/$10-gift-certificate is really what you mean for the old url and I don't know what [subdomain] maps to. Which in that case you would want this.

 RewriteRule /?item/(.+?)/?$ product.php?ID=$1 

Which given the same input above would output

 http://site1.domain.com/product.php?ID=12357/$10-gift-certificate 

So you see that the client sees the new url, but the server sees the old one. Which is why I said most people look at this backwards, in the beginning.

Anyway, here is a site to test url rules on

http://htaccess.madewithlove.be/

I am sure there are other sites out there too.

Upvotes: 0

Related Questions