+ Start a Discussion
3 Creeks3 Creeks 

Retrieve public URL for a salesforce site

Does anyone know if I create a Salesforce Site and associate a VF page with it, can I retrieve the site's public URL given the VF page name using SOQL? Thanks
Best Answer chosen by 3 Creeks
Vasani ParthVasani Parth
You can query on the Site object and construct the URL, 
Site site = [SELECT Subdomain, UrlPathPrefix FROM Site];
String url = 'https://' + site.Subdomain + '.secure.force.com/' + site.UrlPathPrefix;

System.debug(url);
/* https://myname.secure.force.com/mysite */

 

All Answers

Vasani ParthVasani Parth
You can query on the Site object and construct the URL, 
Site site = [SELECT Subdomain, UrlPathPrefix FROM Site];
String url = 'https://' + site.Subdomain + '.secure.force.com/' + site.UrlPathPrefix;

System.debug(url);
/* https://myname.secure.force.com/mysite */

 
This was selected as the best answer
3 Creeks3 Creeks
Yeah, that basically works but still do not know how to query the site based on the visualforce page it uses.  I guess I will get around that by requiring the user to use a specific name for the site.  Here is what I came up with in case others are interested:
 
public static String getSiteUrl() {
		String siteUrl = '';
		String hostName = URL.getSalesforceBaseUrl().getHost().replace('visual.', '').replace('salesforce', 'force');		
		try {
			List<Site> s = [Select UrlPathPrefix, Subdomain, name From Site where Name = 'MySite'];
			if ( !s.isEmpty()  && s.size() == 1) {
				siteUrl = 'http://' + s[0].Subdomain + '.' + hostName + '/';	//Using http is safer.  If "require https" is enabled, http will get redirected to https
				if (String.isNotBlank(s[0].UrlPathPrefix)) {
					siteUrl += s[0].UrlPathPrefix;
				}
			}
		} catch (QueryException e) {
			system.debug('Exception caught querying Site table. ' + e.getMessage());
		}
		return siteUrl;
	}