They don’t. Drugs are molecules, and in spite of what homeopathy says, molecules have no brain, no desire and no memory. They will perform random motion depending on the corresponding Gibbs free energy.
Therefore, the drug you swallow needs to be designed so that it either survives the stomach, duodenum, liver-produced enzymes, pancreas-produced enzymes, gall, and whatever else it encounters on its was to the small intestine from whence it can be absorbed into the blood stream or it must be modified only in ways that are favourable to the pharmacist. Then, second obstacle: the blood enriched with nutrients and other compounds coming from the intestines is passed by the liver where a number of enzymes takes care of everything the body does not approve of; the drug either again needs to survive this or be modified in a favourable way. This is tested in screenings.
Henceforth, the active ingredient is in the blood stream, and it randomly follows the direction the blood takes. Some of your headache medicine will end up in your left toe, some in your little finger, some will circle the heart via the coronary arteries and so on. Only some will actually go to the brain where it is supposed to have an effect. And while passing through the brain in the blood stream, only some of the molecules actually exit to enter the tissue. Remember also, that the brain is pretty special amongst destinations in the body due to the blood-brain barrier.
Then, finally selectivity. If you are lucky, the drug will fit selectively only into a pocket of one or a select few enzymes, selectively inhibit or enhance their function and thereby cause a physiological effect. However, you might be unlucky and have a less specific drug. In that case, you experience what is known as side effects.
Pharmaceutrical companies spend a lot of money on designing drugs and testing them so that they perform maximally well (‘maximally’ defined in pharmacological terms) and have minimal side effects. Yet, sometimes something critical is missed; one of the most well-known cases may be contergan, but for example there have been recent cases of contraceptive pills causing embolies, iirc.