Sam
Sam

Reputation: 15506

Optional Regex for URL Rewriting: How to make a part of URL fully optional?

a short question about optional regex:

imagine a given page thats currently rewritten/beautified to:

/xx/somepage/description-description-description

while actually loading the ugly url below water:

/somepage?ln=xx

via this seemingly working rule:

RewriteRule ^([a-z][a-z])/(.*)/(.*?)$ /$2?ln=$1 [L]

However, currently the last portion /description is now compulsory. Without it error 404 occurs. What RewriteRule should I use to make the third and last part optional? Especially since it has no file-fetching meanings and is only for the user to make a url more descriptive.

In other words, I would like all three of the below to work the same way:

/xx/somepage
/xx/somepage/description-description-description

thanks very much

update

both of these seem to work fine:

RewriteRule ^([a-z][a-z])/(.*?)(/.*)?$   /$2?ln=$1 [L]
RewriteRule ^([a-z][a-z])/([^/]+)(/.*)?$ /$2?ln=$1 [L]

the difference being on the the middle part. I gather it has something to do with greedyness... but why/how they differ exactly... someone else might be able to shed light here.

Upvotes: 1

Views: 1749

Answers (2)

skue
skue

Reputation: 2077

You may need to ensure that the second pattern doesn't include a slash:

RewriteRule ^([a-z][a-z])/([^/]+)(/.*)?$ /$2?ln=$1 [L]

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101614

Remove the final / in your rule, or place it in an optional group. As it stands, and from what I see, the description isn't completely necessary, but a trailing slash is.

New RegEx:

RewriteRule ^([a-z][a-z])/(.*?)(/.*)?$ /$2?ln=$1 [L]

Upvotes: 2

Related Questions