Skip to content
/

Translating URLs using Alternate Access Mappings from code

With SharePoint it is easy to configure multiple zones for your SharePoint Web Application. For example, you have a Publishing Web Site with two zones.

  1. The authenticated CMS where editors can manage content: https://cms.int
  2. The anonymous website where everybody can view the content: http://www.ext

When the editors link to sites, pages, documents and images the URL will start with https://cms.int. After the content is published it’ll also be available on the anonymous site. Now most of the URLs will be automatically translated to corresponding zone URL and start with http://www.ext.

However, there are some places where this is not the case. You could try to use relative URLs but even that will not fix every scenario.

Translate the URL using code

Facing this issue, I had to translate the URLs myself. But I want to write minimal code. Luckily, Microsoft has done most of the work for me.

On the SPFarm class you will find the AlternateUrlCollections property. This “collection” is actually an instance of the SPAlternateUrlCollectionManager class and provides the RebaseUriWithAlternateUri method.
And this is where the magic happens.

This method has an overload where you supply a Uri and a SPUrlZone. You can provide one of the values of the SPUrlZone enumeration or you can provide the current zone.

To get your current zone you can use the static Lookup method of the SPAlternateUrl class. This method requires a Uri so we provide the current one using the ContextUri property from the same class.

To wrap it all up I give you the code:

var originalUri = new Uri("https://cms.int/pages/default.aspx");

var zone = SPAlternateUrl.Lookup(SPAlternateUrl.ContextUri).UrlZone;

var translateUri = SPFarm.Local.AlternateUrlCollections
                                    .RebaseUriWithAlternateUri(originalUri, zone));

// When accessing from the authenticated zone
// translateUri == "https://cms.int/pages/default.aspx"

// When accessing from the anonymous zone
// translateUri == http://www.ext/pages/default.aspx

“Other” URLs

If you pass a URL which is not listed as an Alternate Access Mapping the method will return the original URL.