Brian Fleishman
Brian Fleishman

Reputation: 1257

Extracting the Domain from the URL using ColdFusion

I am currently using CGI variables to extract the full URL and the hostname from the current URL:

<cfset currentURL = CGI.SERVER_NAME>
<cfset host = ListFirst(currentURL, ".")>

The previous code works as expected.

I would like to also extract the domain. I can't find a CGI variable for that surprisingly, and I have tried the following code but it does not seem to work:

<cfset domain = ListLast(currentURL, "#host#")>

But the domain variable is only showing 'om' instead of 'domain.com' when I output it. What am I doing wrong here?

Upvotes: 4

Views: 2533

Answers (2)

Jules
Jules

Reputation: 2019

The full URL would be:

'#getPageContext().getRequest().getScheme()#://#cgi.server_name#/#cgi.script_name#?#cgi.query_string#'

That will include protocol, path, and url variables.

The domain name is simply #cgi.server_name#.

Upvotes: 1

Nichoru
Nichoru

Reputation: 41

This is one way to do it and it will handle domains with multiple subdomain parts (e.g., local.dev.mydomain.com).

<cfset currentURL = CGI.SERVER_NAME>

<cfset domainParts = listLen(currentURL, ".")>

<cfset domain = gettoken(currentURL,domainParts-1,".") & "." & gettoken(currentURL,domainParts,".") >

Upvotes: 1

Related Questions