How can I automatically redirect visitors of my website to its onion version if I detect that they're Tor users?
With 100% accuracy? You can't.
You can use tools like TorDNSEL and lookup each incoming user through a DNS query to discover if they're using a known Tor exit.
Alternatively you can use the TorBulkExitList to export the current set of relays that allow exiting to your service. This list will get stale though.
There are always being to be edge cases where an IP is no longer in use as a Tor exit but it is on the list and you would redirect them to the .onion and they wouldn't connect. Similarly there will be Tor users whose IP isn't on the list that you don't redirect.
Some other approaches, which are more accurate, would be to test in the browser itself if they can connect to .onion addresses. Putting a tag like
<script src='http://foo.onion'> and having the loaded script redirect users to the .onion website would let you redirect users who could fetch resources from the .onion but not those who couldn't.