chaoskreator
chaoskreator

Reputation: 914

Url RewriteRule conditionals

I am working on some SEO for my site, and using urls like category/this-cat.html and category/this-cat-p2.html to redirect to index.php?mode=viewCat&id=this-cat and index.php?mode=viewCat&id=this-cat&start=10 respectively. The problem is that my RewriteRule needs a conditional to check if the -p2 part is present in the URL, and then return either 0 or the digit after p.

Current rule:

RewriteRule ^category/(.*?)\.html$ index.php?mode=viewCat&title=$1

I would have thought that the correct syntax for this would have been:

RewriteRule ^category/(.*?)(?(-p)(.*?)|0)\.html$ index.php?mode=viewCat&title=$1&start=$2

however, this causes the server to return a 500 error. Even after having read tutorials and worked with them for the past week, I still have little grasp on them. Can anyone explain how to make a conditional like this work?

Upvotes: 3

Views: 89

Answers (1)

Jason McCreary
Jason McCreary

Reputation: 72961

You're close. I believe what you are trying to do is not capture the optional -p# grouping, but want the digit if it exists. The non-capture flag for a group is a ?: prefix.

RewriteRule ^category/(.*?)(?:-p(\d+))?\.html$ index.php?mode=viewCat&title=$1&start=$2

Note: I used \d (digit) as it's better to be specific about what you are matching. Also start will have a digit or nothing. Your server-side code is better suited to handle the rest of the logic you described.

Upvotes: 2

Related Questions