Your body recognizes pain with nerve cells called nociceptors. When nociceptors are triggered to fire (i.e. send a nerve impulse, known as an action potential), they cause a cascade of chemical reactions that result in the experience of pain.
One class of chemicals, called prostaglandins, plays a key role in the progression of this chemical reaction. Drugs like ibuprofen and aspirin block prostaglandin, therefore preventing the remaining reaction cycle and as a consequence, pain.