Nibhrit
Nibhrit

Reputation: 188

Optional parameters in URL - rewrite rule

I don't know if the word "optional parameters" correctly describes my situation. Here is what I need.

I wrote the following rule for URL redirection:

RewriteRule ^product/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)$ product/?sid=$2&pid=$3&title=$1&src=$4 [NC,L]

Basically, this will redirect something like

http://localdomain.com/product/Golf-Bats/abc123/def456/stringy

to something like

http://localdomain.com/product/?sid=abc123&pid=def456&title=Golf-Bats&src=stringy

What I want to do is write a rule that takes in additional/optional/potentially-infinite-number of parameters ( // type constructs) but still redirect to the same URL.

That means the following URL s:

http://localdomain.com/product/Golf-Bats/abc123/def456/stringy
http://localdomain.com/product/Golf-Bats/abc123/def456/stringy/rand1
http://localdomain.com/product/Golf-Bats/abc123/def456/stringy/rand1/rand2
http://localdomain.com/product/Golf-Bats/abc123/def456/stringy/rand1/rand2/rand3
etc.

should all just point to the URL

http://localdomain.com/product/?sid=abc123&pid=def456&title=Golf-Bats&src=stringy

Any ideas?

Upvotes: 2

Views: 5514

Answers (1)

LazyOne
LazyOne

Reputation: 165188

Use this rule -- it will make 6th and further path segments "optional":

RewriteRule ^product/([a-z0-9\-]+)/([a-z0-9\-]+)/([a-z0-9\-]+)/([a-z0-9\-]+)(/.*)?$ product/?sid=$2&pid=$3&title=$1&src=$4 [NC,L]

This rule will treat all these URLs as the same (will redirect to the same URL):

http://localdomain.com/product/Golf-Bats/abc123/def456/stringy
http://localdomain.com/product/Golf-Bats/abc123/def456/stringy/rand1
http://localdomain.com/product/Golf-Bats/abc123/def456/stringy/rand1/rand2
http://localdomain.com/product/Golf-Bats/abc123/def456/stringy/rand1/rand2/rand3
  1. I have replaced A-Za-z by a-z in pattern since you already have [NC] flag (ignore case).

  2. Keep in mind that this sort of URLs in general are not good from SEO point of view - I strongly recommend using <link rel="canonical" href="PROPER_URL" /> to specify proper URL to avoid duplicate content penalty from search engine:

  3. That "optional" part will be lost / not be passed to new URL -- as requested.

Upvotes: 3

Related Questions