Every time I stretch for a few minutes, I seem to be more flexible than before. But, after a few hours of resting, the flexibility gained seems to be lost again and my flexibility is back where I started before the first stretching, meaning I gained little/nothing. How do I prevent this from happening?
The only way to gain "permanent" flexibility is to stretch chronically. Every time you stretch you will be giving your muscles an insignificantly small amount more length, that'll revert if you don't stretch often enough, but stretching chronically you will be able to add up those extremely small lengths into noticeable flexibility that lasts. You will need to continue stretching to maintain that though, as the body is always working to return to a "neutral" position.
This video here is a great resource on the subject if you have 45 minutes to spare, and will describe everything far more sufficiently than I could.