The fruit first arrived in Japan during the Edo period, and due to it's fibrous nature it was known as 糸瓜: thread gourd. いとうり became shortened to とうり, and this name was current for a while. The modern word is へちま, which is derived from the older form.
In order to explain how, we have to take a bit of a diversion.
In modern Japanese, the kana is ordered in あいうえお order. It's a nice, straightforward way of systematically ordering the characters. However, formerly a more poetic order was favoured.
The いろは poem uses each kana once, and at the same time including some rather esoteric Buddhist philosophy.
The important part is in the first two lines of this poem.
A loofah is とうり, a 'と gourd'. と is between へ and ち in いろは order. 間 means 'space' or 'between', so へちま means between へ and ち. Therefore (?) とうり is へちま. This probably started life as a riddle, but for some reason it caught on as the actual name for a loofah, to the point where とうり isn't even a word for it any more. But the original name lives on: へちま is still written in kanji as 糸瓜.