Apache Sling Rewriter : how to rewrite urls in AEM\CQ5

The Apache Sling Rewriter is a module which helps us to rewrite the output generated by the sling processing engine,  we can use sling rewrite to solve

  • Rewrite URL to CDN based URL’s
  • To generate HTML by combining XSLT and XML
  • Generate pdf file using XSL:FO
  • Shorten URL’s
  • To generate SEO friendly URL’s
  • etc…

As part of this article, I am taking a simple example which scans requested page for image:src attributes and rewrites it to CDN supported URL’s for this I am going to write custom CDNTranformation which extends from AbstractSAXPipe and implements from org.apache.sling.rewriter.Transformer

The Apache Sing Rewriter uses SAX Pipelines, here I am using Apache Cocoon which is an xml based SAX pipeline to rewrite sling generated output

The SAX Pipelines contains three components generator, transformer, and serializer, the generator gets the output from the sling and then pass it to the transformer, the transformer contains several SAX events but here we are using startElement event to rewrite URL’s, once all SAX events execution completed then it passes to the serializer, the serializer collects all SAX events and generate output

The first thing which we need to do is create a custom CDNTransformerFactory which implements from org.apache.sling.rewriter.TransformerFactory and this should be registered as a service, we need to define unique name for this service through pipeline.type property, this service will have createTransformer method which returns new instance of the transformer

Some requirements may demand to execute custom transformer globally in that case you need to use pipeline.mode =”global” , it just adds this transformer to the existing pipeline, along with this we need to use service.ranking to tell when to execute this custom transformer, if it greater than zero then executes at the end of the transformer and before the serializer but the problem with this is it executes for every request which may impact on performance

You can use pipeline.type property to execute specific to your project by providing unique name and calling this uniquename in the project specific configuration

The below CDN Transformer Factory returns new transformer instance

The below CDNTransformer has a method called startElement where you can get all attributes of the elements. iterate every element and get the image src object and prefix with cdn url

In the pom.xml file we need to add below dependency

We need to override cofig folder to /apps/aemtoolkit/config/rewriter/aemtoolkit.xml by adding below configuration entries



  • Thiago C. C.

    Hi there,
    I’m getting an error:
    Caused by: java.io.IOException: Unable to get component of class ‘interface org.apache.sling.rewriter.Transformer’ with type ‘cdnrewriter’.
    I can see the installed bundle. Do you know what I’m missing?
    Thank you!