There is a very simple answer to this. It's all about patents. When a new drug is discovered and patented, it can only be sold by the inventing company over 20 or 50 years (I forget which. Hence when your doctor prescribes the drug, the phamacist can only get it from that one company.
However, when the patent expires the drug can be manufactured by anyone provided they meet strict manufacturing and safety standards set by NICE in the UK or the FDA in the USA. So the drug is now availble from many sources instead of one supplier. The drug is now a part of a group of suppliers armoury. That group of products is now termed "generic". This gives your doctor choice as to whether precribe the original discovering company's product or another (perhaps) cheaper version.
In all cases, if a drug is deemed safe for you to buy by your own judgement it is no longer prescription-only and is made available by supermarkets etc. It is now termed OTC meaning Over The Counter.
Typically, antibiotics like the penicillin group, will never be OTC because uncontrolled use would render them even more widely bacterial-resistant and worthless in killing the bugs.
There are also "midway" drugs termed pharmacy-only e.g. you can only buy them from the chemists like Boots or Lloyds. Hydrocortisone is a typical example.
Sorry about the length of this - maybe you will need an aspirin or paracetamol tablet after the headache of reading this, lol.
Regards,
SIQ.