mod-rewritepagination

Mod Rewrite Optional Parameters


I have a fairly complex set of rewrite rules to give my site pages pretty URLs. Right now to deal with paging of search results I'm using 2 rewrite rules:

RewriteRule ^search/([0-9]+)$ /cgi-bin/search.pl?page=$1 [NC,L,QSA]
RewriteRule ^search$ /cgi-bin/search.pl [NC,L,QSA]

These handle URLs such as:

http://example.com/search
http://example.com/search/2
http://example.com/search/1000

I'm wondering how to combine these into 1 rewrite rule so that the search.pl script is called correctly and only passed the page parameter if a page is specified. I know it's a pretty basic question but I can't seem to find the answer anywhere.


Solution

  • You could do something like this:

    RewriteCond page=$2 ^page=.+|
    RewriteRule ^search(/([0-9]+))?$ /cgi-bin/search.pl?%0 [NC,L,QSA]
    

    But that’s not really nicer, is it?


    Edit    Or if you’re fine with an empty page value:

    RewriteRule ^search(/([0-9]+))?$ /cgi-bin/search.pl?page=$2 [NC,L,QSA]