"horizontal bar passing from one post or support to another," c. 1300, from Old French raille, reille "bolt, bar," from Vulgar Latin *regla, from Latin regula "rule, straight piece of wood," diminutive form related to regere "to straighten, guide" (from PIE root *reg- "move in a straight line").
In U.S. use, "A piece of timber, cleft, hewed, or sawed, inserted in upright posts for fencing" [Webster, 1830]. Used figuratively for thinness from 1872. By 1830s as "iron or steel bar or beam used on a railroad to support and guide the wheels." To be off the rails "out of the normal or proper condition" in a figurative sense is from 1848, an image from railroads.
Old English heawan "to chop, hack, gash, strike with a cutting weapon or tool" (class VII strong verb; past tense heow, past participle heawen), earlier geheawan, from Proto-Germanic *hawwanan (source also of Old Norse hoggva, Old Frisian hawa, Old Saxon hauwan, Middle Dutch hauwen, Dutch houwen, Old High German houwan, German hauen "to cut, strike, hew"), from PIE *kau- "to hew, strike," a root more widely developed in Slavic (source also of Old Church Slavonic kovo, Lithuanian kauti "to strike, beat, fight;" Polish kuć "to forge," Russian kovat' "to strike, hammer, forge;" Latin cudere "to strike, beat;" Middle Irish cuad "beat, fight").
Weak past participle hewede appeared 14c., but hasn't yet entirely displaced hewn. Seemingly contradictory sense of "hold fast, stick to" (in phrase hew to), 1891, developed from earlier figurative phrase hew to the line "stick to a course," literally "cut evenly with an axe or saw." Related: Hewed; hewing.