+ Start a Discussion

How to get the site url from Apex Code

Hi Guys,


Is thera any way I can got the site url from Apex Code?


I tried Site.getPrefix() , Site.getDomain() and getCurrentSiteUrl. but all of them return null.


Do I need setup some information after the site is ready. 


Thanks in advance.




Best Answer chosen by Admin (Salesforce Developers) 

In this case I tend to store that information in a custom setting. 

All Answers

Software Allies TeamSoftware Allies Team

if Site.getPrefix is null, then try 

Tejpal KumawatTejpal Kumawat

Hi try to this it will be definately works...


public String getSiteUrl(){
return Url.getSalesforceBaseUrl().toExternalForm();


Thanks guys,


For Page.largeLookup.getUrl(), I got a compile error "Page largelookup does not exist"


from Url.getSalesforceBaseUrl().toExternalForm(), the result like https://na12-api.salesforce.com. which is salesforce internal domain.


Is it possible to get the salesforce.com site domain name something like http://XXX.force.com ?


What I am doing is to make the attachments public via force.com site,  the url pattern for attachment is {!$Site.Prefix}/servlet/servlet.FileDownload?file={!List.Image},


Unfortunately, I have to expose those the attachment image via web service. so I have to get the site domain from Apex Code.


Or Is there any way to expose images directly?




If Site.getPrefix() or Site.getDomain() returns null, it means that the request is not running in the context of sites.


Yes, I am trying to get url in Apex web service.   Is there any method I can call in web service?


In this case I tend to store that information in a custom setting. 

This was selected as the best answer

Thanks, customer setting is a good solution :)