views:

36

answers:

1

Sorry to bug everyone with another mod_rewrite problem but you know the drill.

Basically, I have viewer.php, which accepts two arguments, chapter and page. Sometimes people will request a chapter only, and sometimes they will request a chapter and page. i.e. viewer.php?chapter=10 or viewer.php?chapter=10&page=5. The php is smart enough to display page one for users who don't specify a page, and I don't care about users who request viewer.php?page=3&chapter=50, nobody will do that.

I want to hide viewer.php from the public and make the format c5/p3.html and c5 canonical. i.e. example.com/c5/p3.html displays the results of example.com/viewer.php?chapter=5&page=3 and example.com/c5 displays the results of example.com/viewer.php?chapter=5. If I can I'd also like to catch people who forget the .html, i.e. example.com/c14/p3. In all these cases I want their address-bar URL to change as well as them being served the appropriate viewer.php content.

This is my current attempt at doing that, but it has problems.

## PRETTIFY URLS
# We'll help those who screw it up and forget the .html (i.e. /c12/p3), but..
RewriteRule c([0-9\.]+)/p([0-9]+)?$ /c$1/p$2.html [R=Permanent,NC]
# (this is a vestige of when I thought I wanted /p1.html appended for those who didn't specify a page, changed my mind now)
RewriteRule c([0-9\.]+)(/)?$ /c$1/p1.html [R=Permanent,NC]
# The canonical form is /c12/p3.html and that's that.
RewriteRule c([0-9\.]+)/p([0-9]+).html?$ /viewer.php?chapter=$1&page=$2`

This works great for c1, c14/p3.html and c14/p3. But: by virtue of the second RewriteRule (which I can't figure out how to remove without Apache showing a "Moved permanently" error page that links to itself) it transforms c5/ into c5/p1.html when I'd rather it just remove the trailing slash and become c5. It also throws a 404 if the user requests c5/p4/ instead of knowing what they meant and transforming it into c5/p4.html.

As an additional problem, I have a form somewhere that uses method="get" to submit a chapter to viewer.php, and in that case the underlying view.php?chapter=5 structure is shown to them in the resultant URL, so maybe I should add a rule that grabs direct requests to viewer.php and puts them in the newer style somehow.

So, could anyone help me with this? I hope I've been clear enough in what I want. It would seem to me that if modifying my existing code, I need to handle trailing slashes better and somehow clean up requests for viewer.php in the c5 style without causing an infinite loop.

Help is so so much appreciated.

A: 

Try these rules:

RewriteRule ^c([0-9]+)/p([0-9]+)/?$ /c$1/p$2.html [R=Permanent,NC]
RewriteRule ^c([0-9]+)/?$ /c$1/p1.html [R=Permanent,NC]
RewriteRule ^c([0-9]+)/p([0-9]+)\.html$ viewer.php?chapter=$1&page=$2
Gumbo
Hey,Thanks a lot. I modified your rules a little but overall you provided what I wanted and I appreciate it - seems very robust. Thanks :)
SuitCase