Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 531
chaoskreator Avatar asked Sep 02 '26 13:09

chaoskreator


1 Answers

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.

like image 186
Jason McCreary Avatar answered Sep 05 '26 02:09

Jason McCreary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!