The two saheehs along with the Musnad and Sunan compilers, recorded that Umar bin Al-Khattab radhiAllahu anhu said that the Messenger of Allah sallAllahu aalyhi wa sallam said,
إِنَّمَا الْأَعْمَالُ بِالنِّــيَّاتِ، وَإِنَّمَا لِكُلِّ امْرِىءٍ مَا نَوَى، فَمَنْ كَانَتْ هِجْرَتُهُ إِلَى اللهِ وَرَسُولِهِ، فَهِجْرَتُهُ إِلَى اللهِ وَرَسُولِهِ، وَمَنْ كَانَتْ هِجْرَتُهُ إِلى دُنْيَا يُصِيبُهَا، أَوِ امْرَأَةٍ يَتَزَوَّجُهَا، فَهِجْرَتُهُ إِلى مَا هَاجَرَ إِلَيْه
The reward of deeds depends upon the intentions, and every person will be rewarded according to what he has intended. So, whoever emigrated to Allah and His Messenger, then his emigration is for Allah and His Messenger. And whoever emigrated for worldly benefits or for a woman to marry, his emigration is for what he emigrated for.
This hadith is general, it applies to Hijrah as well as every other deed.
In the two saheehs, it is recorded that a man killed ninety-nine people and completed the number one hundred when he killed a worshiper. He then asked a scholar if he has a chance to repent. The scholar said, “What prevents you from repentance?” The scholar told the killer to emigrate from his land to another land where Allah is worshiped. When he left his land and started on the migration to the other land, death overtook him on the way.
The angels of mercy and the angels of torment disputed about the man, whereas the former said that he went out in repentance, while the latter said that he did not arrive at his destination. They were commanded to measure the distance between the two lands and to whichever land he is closer to, he will be considered part of that land. Allah commanded that the righteous land to move closer and the land of evil to move farther. The angels found that he died closer to the land that he intended to emigrate to by a hand-span, and thus the angels of mercy captured his soul. In another narration, when death came to that man, he moved his chest towards the righteous village that he emigrated to.