Rebasing Absolute URLs in SharePoint

SharePoint has this funny mechanism ‘Alternate Access Maps’. Essentially, this means that the same content can be available via different web applications, which have different URLs.

But what do you do if you’ve an absolute URL to something in SharePoint, and you need it to be correct for the users’s current alternate access map zone?

Well, there is a function SPUtility.AlternateServerUrlFromHttpRequestUrl() – but I couldn’t see how to use it. Internally, it uses RebaseUriWithAlternateUri() – looks promising. And it works.

string url - "Absolute URL in the wrong zone";
SPUrlZone zone = SPContext.Current.Site.Zone;
Uri currentZoneUrl = SPFarm.Local.AlternateUrlCollections.RebaseUriWithAlternateUri(new Uri(url), zone);

I’m a bit suspicious of using the local SPFarm object, but that seems to work correctly. Others do seem to have done this:

Rebasing Absolute URLs in SharePoint