Not sure this is the problem, but since you say it's cache related, it could be the fact that the top links block is cached and the cache does not take into account the current url.
So if you don't have a cache for it, and the first page you visit is the homepage it will always create the cache containing the homepage url.
You can go around this by adding the current url to the cache key of the block.
You can do this via a plugin.
the top links block is an instance of Magento\Customer\Block\Account\Navigation
as stated in Magento_Theme::view/frontend/layout/default.xml
.
So let's create a plugin for that class:
Add this to frontend/di.xml
in one of your modules.
<type name="Magento\Customer\Block\Account\Navigation">
<plugin name="add-current-url-to-cache-key" type="[Vendor]\[Module]\Plugin\TopLinksPlugin" />
</type>
then create the class [Vendor]\[Module]\Plugin\TopLinksPlugin
namespace [Vendor]\[Module]\Plugin;
class TopLinksPlugin
{
public function afterGetCacheKeyInfo(\Magento\Customer\Block\Account\Navigation $subject, array $cacheKey)
{
$cacheKey[] = $subject->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);
return $cacheKey;
}
}
This will most probably solve your issue, but it comes with a cost.
This means that you will get a different version of the cache for the top links block for each page you have.
An alternative solution would be to create a separate block that you put in the layout near the top links (or where ever you want) and have just that block cached with a cache key that is different from page to page.
Or better yet, display this url via Javascript because you can use it anywhere via window.location
no matter if the page is cached or not.
I don't know what are your exact requirements for this, so I offered multiple solutions.
Just watch out for typos in the first solution. I didn't test the code.