Convert Relative URLs to Absolute

I put this ColdFusion UDF together the other day to turn relative URLs to Absolute. Code is pretty straightforward.

<cffunction name="URLRelativeToAbsolute" returntype="string"
  hint="Converts relative URLs in an element and converts to absolute. It includes the http:// protocol prefix.">  
 
  <cfargument name="content" type="string" required="true" hint="HTML content that will be scanned and replaced." />
 
  <cfargument name="domain" type="string" required="true" hint="Add domain name to relative links." />
 
  <cfset var local = StructNew() /> 
 
  <!--- The following regexp handles the following elements: link, a, img, script, form, frame. --->
  <cfset local.contentFixed = REReplaceNoCase( Arguments.content, "(href|src|action)=""/?((\./)|(\.\./)+|)(?=[^http])", "\1=""http://" & domain & "/", "all" ) />  
 
  <!--- The following regexp handles the url() attribute of the background CSS property. --->
  <cfset local.contentFixed = REReplaceNoCase( local.contentFixed, "url\((\s)?(')?/?((\./)|(\.\./)+|)(?=[^http])", "url(\2http://" & domain & "/", "all" ) />  
 
  <cfreturn local.contentFixed />    
 
</cffunction>

Usage:

<cfsavecontent variable="htmlContent">
<textarea name="data" rows="20" cols="60">
  <style>
    body { 
      background-image:url('stars.png');
      background-image:url('../stars.png');
      background-image:url('/stars.png');
      background-image:url('/../../../stars.png');
    }
  </style>
  <a href="../../../images/shiny.jpg">Shiny</a>
  <a href="http://www.google.com">This should not be touched</a>
  <img border="0" src="/images/cool.png" /> 
  <link rel="index" href="../../index.asp">
  <form method="POST" action="cgi/processing.cgi"></form>  
</textarea>
</cfsavecontent>
 
<cfoutput>
 
  #htmlContent#
  #URLRelativeToAbsolute( htmlContent, "www.shinylight.com" )#
 
</cfoutput>

Result:

Leave a Reply