I'm on doing custom logs, there for I use an internal REST callout to bypass a LimitException rollback.

My page:


Controller code:

    HttpRequest req = new HttpRequest();
    req.setHeader( 'Authorization', 'OAuth '+UserInfo.getSessionId() );
    req.setEndpoint( URL.getSalesforceBaseUrl().toExternalForm() );

like you see, I'm trying to get the server url,


but what URL.getSalesforceBaseUrl() returns is the VF Subdomain URL


This is a known problem, but I'm not able to find a useful solution. Bad practice that I actually use to solve it:

String salesforceHost = URL.getSalesforceBaseUrl().toExternalForm().replace('visual.','sales').replace('c.na','na');

This should return what you want:

private String instanceUrl() {
    String result = null;

    List<String> fragments = URL.getSalesforceBaseUrl().getHost().split('\\.');

    if(fragments.size() == 3) {
        result = fragments[0]; // Note: Apex URL: NA14.salesforce.com
    else if(fragments.size() == 5) {
        result = fragments[1]; // Note: Visualforce URL: mydomain.NA14.visual.force.com

    return result + '.salesforce.com';
  • 1
    Can you add a little more explanation around what fragments you see and why the numbers 3 and 5 are significant?
    – Adrian Larson
    Feb 1 '17 at 15:26

Visualforce is served from a different subdomain to prevent Cross Domain Scripting attacks and other security reasons. Therefore URL.getSalesforceBaseUrl().toExternalForm() in a VF Context returns the subdomain URL (its not the VF Page, rather the VF Subdomain URL)

I'd imagine what you've done is possibly the best work around.


Maybe you could build your required URL using the InstanceName from the Organization object such as:

select InstanceName from Organization

This returns something like NA17 or AP1 etc.

Unlike using 'System.URL.getSalesforceBaseUrl().getHost()' this works in:

Case 1: Any Development Org Case 2: My Domain Enabled Case 3: Sandbox Case 4: Managed Package

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.