views:

33

answers:

1

I have a URL I want to shorten with a mod_rewrite.

In its ugliest form it looks like:

/img.php?i=15&a=92

Ideally it would look like:

/img/15/92

The problem is sometimes it might just be:

/img.php?i=15

In which case the person will enter:

/img/15

So I'm thinking I need a mod_rewrite like this:

RewriteRule ^/img/(.*)/(.*)$ /img.php?i=$1&a=$2

Which I imagine will work only when both variables are in the URL and not just the shortened version.

How do I make a single rewrite that works for both, or how do I make 2 without cancelling the other out?

+2  A: 

Try this rule:

RewriteRule ^img/([0-9]+)(/([0-9]+))?$ img.php?i=$1&a=$3

When using mod_rewrite in a .htaccess file, you need to remove the per-directory path prefix from the pattern (in this case the leading /). Because mod_rewrite does that too and puts back it after the rewrite process.

Gumbo
I have no idea how you go from $1 to $3 without a $2 - but it works. legend Gumbo
cosmicbdog
@cosmicbdog: The second group is the optional one `(…)?` that contains the third group.
Gumbo