Outer ear infections are best prevented by avoiding contamination of your outer ear canal. If you have never had an outer ear infection then you likely don't have to take any precautions. But if you have a propensity to get outer ear infections, you want to be very careful when you swim not to get water in your ear. You want to be careful when you shower not to turn your head and intentionally get water in your ear. And, you want to be very careful not to manipulate your ear with any foreign body, such as a Q-tip or a hairpin.
There are drops that are available over the counter that change the environment in your ear and prevent infections. They don't need a prescription, and you can go into any pharmacy and get such a drop, and if you use it regularly, it will make it less likely that you will get an outer ear infection.
Middle ear infections are most common in children, and the only real way to avoid these infections is to isolate your child. Children most often pick up these ear infections when they go to school, because unfortunately, kids come to school when they're sick and they spread these infections around.
In children, most middle ear infections are due to an upper respiratory tract infection, either a cold, or a sinus infection, or bronchitis, and that is highly contagious. So if your child has a history of infections and you're getting ready to go on your vacation to the Bahamas, keep your child out of school for a week, the likelihood is they will not get a middle ear infection.
Unfortunately, there's no way to prevent inner ear infections. Viruses are ubiquitous, they catch us when we least expect, and there is no way to avoid them.