Forum Moderators: phranque

Message Too Old, No Replies

mod rewrite with dynamic number of parameters

         

rizoto

11:05 pm on Jan 11, 2008 (gmt 0)

10+ Year Member



Hello,

I'm trying to figure out how to use mod_rewrite to transfer control to a php file when sometimes there's a parameter in the request and sometimes not:

I have a page that generates some list (list.php). I want the link in my site to show: mysite.com/list.html which will send the user to the list page like this:
RewriteRule ^list.html$ list.php?page=1

But how do I handle the same if I want to keep an option to support pagination? (mysite.com/list-2.html for the second page of list values).
The only solution I have is to add an extra line in the .htaccess file:
RewriteRule ^list-([0-9]+)$ list.php?page=$1

I want to avoid the second line if possible and do all in one line.
I consider mysite.com/list-.html not valid. Either list.html or list-pagenumber.html are valid pages.

Is it possible in one line?

Thank you

jdMorgan

11:47 pm on Jan 11, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



> Is it possible in one line?

No, not really. Why is it important to you to avoid using two rules? This is somewhat like saying, "I'll use PHP, but the script can only have one line of code in it."

Please clarify.

Thanks,
Jim

rizoto

11:56 pm on Jan 11, 2008 (gmt 0)

10+ Year Member



Hi,

Thanks for the quick reply.
It's not that I mind doing it in two lines, it's just that I'm trying to learn in the process and I thought that there might be a regexp that would work.

Basically I'm trying to create a group of the page number but only if it's a number and there's a preceding dash, otherwise the group can be empty.

I decided to use:
RewriteRule ^list\.html¦^list-([0-9]+)\.html$ list.php?page=$1 [nc]

Which, I guess, is exactly like doing it in two different lines.

If you can think of any other option please let me know

Thank you

jdMorgan

1:08 am on Jan 12, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



As long as it is acceptable that the name/value pair passed to your script is "page=" without a value, then that should work. You can also shorten it up a bit using:

RewriteRule ^list(-([0-9]+))?\.html$ /list.php?page=$2 [NC,L]

If it is not acceptable that the value for "page" be blank, then two rules are required:

RewriteRule ^list-([0-9]+)\.html$ /list.php?page=$1 [NC,L]
RewriteRule ^list\.html$ /list.php?page=1 [NC,L]

Jim

rizoto

11:41 am on Jan 12, 2008 (gmt 0)

10+ Year Member



Thanks again for the reply,

The first rule you proposed in the last message is exactly what I'm looking for and I learned something new :)

Thanks