Wednesday, October 08, 2008

Visualforce Tip: How to Determine a Hostname

It isn't entirely obvious how a developer can determine the hostname (server url) portion of the absolute path for a Visualforce page via Apex. Luckily, it is rather easy to do.

You might have already figured out that the PageReference class's getUrl() method will return the relative path for your Visualforce page:

Once you have the relative path for the page, then there's just one remaining trick to discover - the Map returned by the PageReference class's getHeaders() method contains a 'Host' key whose associated value is the hostname for your salesforce org:

The complete code for constructing the absolute path for a Visualforce page is below:

String hostname = ApexPages.currentPage().getHeaders().get('Host');
String pageUrl = ApexPages.currentPage().getUrl();
String absolutePath = 'https://' + hostname + pageUrl;
system.debug(absolutePath); //example output: ''


Jeff Douglas said...

Nice solution. Any idea how to get the url using Apex? The only thing I can think of is looking at the org id and see if it is our production org id.

Jesse Lorenz said...

Jeff - Determining the host from within Apex, but outside of the context of Visualforce is a bit harder. Here are some work-arounds:

Unknown said...

I tried this. The issue is that the URL generated is of Visualforce like
Contact Link:

Is there a way to get the URL like Without parsing it?