Usually a cat does this to transfer their scent to you and identify you as belonging in their world. It’s also used as a sort of friendly greeting while at the same time marking you as ‘approved’.
They begin this behavior as kittens with their mother to greet her and to solicit food. Adult cats will often do the same with humans for the same purpose.
In the same way, when cats are rubbing their heads against a hard object, they are really marking their territory. Although they do look like they are deriving some pleasure from it too.