Richard Dawkins's book, The God Delusion (pages 172-173), provides a pretty good explanation of this evolutionary behavior. I'll try to summarize it.
Moths use celestial objects such as the sun, moon, and stars for navigation. Since these light sources are at optical infinity, the light rays coming from them are essentially parallel and can be used as a compass. For example, "fly so that the moonlight is always at 30 degrees to your eye". For objects at optical infinity, this relationship will never change.
But modern lights are not at optical infinity because they are much closer than the moon and stars; their light rays diverge like spokes on a wheel. Thus, if a moth is navigating using the 30 degree rule, it will end up always turning towards the light. Try keeping any object directly to your right as you move and you'll end up turning towards it!
Unfortunately, moths have not yet evolved to deal with relatively new inventions of lights. This is also why moths seem kill themselves in candles.
Dawkins, Richard. "The God Delusion" p. 172-173