Nerve endings exist in a more or less homeostatic interstitial fluid medium which when disturbed in certain ways result in depolarization. This is a very simple explanation, but basically correct. Depending on the nerves being discussed, a change in the medium can be the presence/absence of neurotransmitters (serotonin, GABA, etc.), chemicals released from damaged tissue, pH differences, etc. etc.
Very simply put, anything causing irritation of the bladder or urethral mucosa will cause some of the nerve endings to depolarize; these are some of the same nerves that depolarize when the bladder is full, and therefore the sensation is of urgency (the feeling that one needs to urinate). The substances can be substances excreted by bacteria, released by neutrophils, or some other.
Simply administering a topical anesthetic - something that decreases the depolarization of nerve endings by reversibly binding to/inactivating sodium channels - (lidocaine, for example) will instantly alleviate this sensation. In the case of UTIs, a commonly given medication is the bladder anesthetic phenazopyridine hydrochloride.
The more complex answer is that no one exactly knows. The complexity is more important in the treatment of non-infectious causes of urinary urgency and in the investigation of why catheter-related UTI are often asymptomatic.
Edited to add: If you're looking for a more teleological reason (such as, it hurts so that you'll get flush out the bacteria faster, that's not actually what happens. When it hurts to urinate, very many women intuitively stop drinking fluids in an attempt to avoid the pain of urination, allowing the infection to get much worse. The counterintuitive measure is to drink more, not less, to flush out bacteria.