I've recently started to need a URL shortener service for one of my web sites. I thought about farming it all out to some other company, but realized that the domain I need to shorten URLs for is incredibly short already. So, I'm creating an in-house URL shortener. Here's how it's laid out in theory:
1. .htaccess sees an incoming request for a URL with a page name beginning with "Z" (for example, example.com/Z00101 since nothing I have begins with a capital Z, this seems like an OK flag) and 301's it to /short.php
2. short.php extracts the page code from the forwarded address and looks up the full address in the database.
3. short.php squirts out its own 301 to the final destination.
That first external redirect should really be an internal rewrite instead.
That is, your RewriteRule should target the internal script filepath, and should not target a URL with domain and protocol.
Use the [L] flag, and do NOT use the [R] flag.
The script will work exactly as it does now, and any request will see only a single 301 redirect. Ensure that requests for Z are not NOT redirected from non-www to www before the rewrite. Exclude the Z path from your canonicalisation rule, because the script will do all the work.
That is, both example.com/Z0001 and www.example.com/Z0001 should access the script and be redirected by the script. There should be no prior non-www/www redirect for *those* requests.