Because of history: both months were set to 31 days in the Roman calendar (July for Julius Caesar, August later adjusted for Augustus).
Explanation
The modern month lengths come from Roman calendar reforms, not from any astronomical necessity.
- Julius Caesar’s calendar reform (the Julian calendar, 46 BCE) reorganized the year and fixed many month lengths. The month originally called Quintilis was renamed July in his honor and was given 31 days.
- Later, the month Sextilis was renamed August for the emperor Augustus (about 8 BCE). Tradition and later accounts say Augustus adjusted month lengths so that the month named after him would not be shorter than July; as a result August was given 31 days as well. A popular story says a day was taken from February to do this — that part is plausible but historians debate the exact administrative details.
When the Gregorian reform of 1582 adjusted leap-year rules, it did not change month lengths, so July and August remain 31 days today.
Bottom line: July and August both have 31 days because of political/historical decisions in Roman times (honoring Julius and Augustus), not because of any natural or astronomical reason.