All posts

AEM URL Shortening: Sling Mappings vs Dispatcher Rewrites

Daniel Strmečki

URL shortening or mapping is a crucial aspect of modern web development, so the same is valid in Adobe Experience Manager (AEM) projects. Short and user-friendly URLs improve user experience, enhance SEO, and ensure consistency across multiple channels. AEM default URLs are not SEO optimized, as they always contain the extra "/content" path prefix, as well as usually a path to the site or market. Let's not forget the unnecessary .html suffix. Here is an example default AEM URL to a page:

  • http://www.meticulous.digital/content/meticulous/uk/en.html

Usually, we aim to make the URLs shorter and keep only the necessary parts, like:

  • http://www.meticulous.digital/uk/en

AEM provides two primary mechanisms for achieving URL shortening or mapping: Sling Mappings and Dispatcher Rewrites. In this article, we'll explore how to achieve the desired behavior using both approaches. We'll compare their configurations, use cases, advantages, and limitations to help you make informed decisions for your AEM projects.

Sling Mappings

Sling Mapping relies on the Sling Resource Resolver, a key feature of AEM that transforms internal repository paths into external-friendly URLs and vice versa. Sling Mapping is configured in JCR, at the /etc/map location, where we can define rules that translate repository paths into shortened URLs. Sling evaluates mapping rules in the order they appear in the repository node structure. If a request matches the sling:match pattern of a rule, that rule is applied, and Sling stops evaluating further rules for that request.

Let's take a look at the example Sling Mapping configuration for creating short URLs. The below-provided configuration is created in the following location:

  • /etc/map/local.meticulous.com.8080

Please note that the sling:Mapping node name is used to enable local testing by:

  • Using port 8080 as the default Apache/Dispatcher local port on AEM SDK.
  • Adding an entry 127.0.0.1 local.meticulous.com to the hosts file to simulate a live domain name pointing to a local machine.

In case we test on an actual AEMaaCS environment with a real domain, then we would use the real domain name without a port number, as it defaults to 80 for HTTP and 443 for HTTPS.

<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
          jcr:primaryType="sling:Mapping"
          sling:internalRedirect="[/content/meticulous/com,/content/dam/meticulous/com]">
    <without_mapping
        jcr:primaryType="sling:Mapping"
        sling:match="*/(bin|api|etc|libs)(.+)$"
        sling:internalRedirect="[/$1$2]" />
    <map-sites-and-dam
        jcr:primaryType="sling:Mapping"
        sling:match="(.+)$"
        sling:internalRedirect="[/content/meticulous/com/$1.html,/content/dam/meticulous/com/$1]" />
</jcr:root>

Now, let's explain the rules in the provided configuration:

  • The without_mapping rule matches requests to custom APIs (like /api or /bin) and AEM APIs (like /etc and /libs) and does not transform them. This rule ensures that requests like /etc.clientlibs/meticulous/clientlibs/my-custom.min.js remain unchanged.
  • The map-sites-and-dam rule matches all other requests and tries to map pages to /content/meticulous/com (adding the .html extension) and assets to /content/dam/meticulous/com. This rule ensures that page requests like http://local.meticulous.com:8080/uk/en are mapped to /content/meticulous/com/uk/en.html, and asset requests like http://local.meticulous.com:8080/images/hero.jpg are mapped to /content/dam/meticulous/com/images/hero.jpg.

The sling:internalRedirect property on the sling:Mapping root node enables us to use the Sling's Resource Resolver API to generate the correct links for our output HTML. This API helps developers provide short and user-friendly URLs when liking other internal pages. The example below demonstrates injecting a Resource Resolver and generating a short URL in a Sling Model.

@SlingObject
private ResourceResolver resourceResolver;

// For path /content/meticulous/com/uk/en returns http://local.meticulous.com:8080/uk/en
public String getShortUrl(String aemPath) {
    return resourceResolver.map(aemPath);
}

Finally, to test our solution with a local instance of Apache/Dispatcher, we'll need to create a virtual host and farm configuration for our domain. In the meticulous.vhost file we can use the defaults but make sure to configure:

  • ServerAlias local.meticulous.com
  • DocumentRoot "${DOCROOT}/content/meticulous/com"

In the meticulous.farm file we can use the defaults but make sure to configure:

  • /virtualhosts { "local.meticulous.com:8080" }
  • /0999 { /type "allow" /url "/uk/*" }

The last line should be added to the /filter section of the farm configuration to allow for requests without extensions. Since this might make it harder to whitelist all the paths, an alternative approach may be to append the .html extension to the incoming URL in Apache/Dispatcher. This can be achieved by adding the rewrite rule to the virtual host configuration.

RewriteRule ^/([a-zA-Z]{2})/([a-zA-Z]{2})(/.*)?$ /$1/$2$3.html [PT,L]

Note that in case we decide to append the .html extension in Apache/Dispatcher, then we need to remove it from the map-sites-and-dam Sling Mapping rule. Finally, a useful tool is available in AEM's System Console to test how our Sling Mapping rules resolve and map.

Dispatcher Rewrites

Dispatcher Rewrite operates at the Apache, web server level, modifying URLs before they reach the AEM instance. Dispatcher Rewrite rules are defined in the virtual host configuration, typically using the mod_rewrite module for Apache. These rules are executed in Apache/Dispatcher, so they don't rely on Sling's Resource Resolver.

Let's examine an example Dispatcher Rewrite rule for creating short URLs. As in the previous example, to test our solution with a local instance of Apache/Dispatcher, we'll need to create a virtual host and farm configuration for our domain. We can rely on the defaults and add just one rewrite rule to support short-to-long URL mapping.

RewriteRule ^/([a-zA-Z]{2})/([a-zA-Z]{2})(/.*)?$ /content/meticulous/com/$1/$2$3.html [PT,L]

Now, let's explain the rules in the provided configuration. We'll start by looking at the pattern:

  • /([a-zA-Z]{2}) - Matches the first two-letter segment after the first slash.
  • /([a-zA-Z]{2}) - Matches the second two-letter segment after the second slash.
  • (/.*)? - Optionally matches any additional path segments after the country and language codes.

Then, let's look at the target /content/meticulous/com/$1/$2$3.html, where:

  • $1 - Represents the first market (like uk or us).
  • $2 - Represents the language (like en or fr).
  • $3 - Represents any additional segments after the language codes (like /about-us).
  • .html - add the .html extension to the end of the URL.

Finally, let's look at the meaning behind the flags:

  • PT (Pass Through) - Treat the rewritten URL as if it were a new request to be processed further. This is necessary for the URL to be properly handled by AEM.
  • L (Last): Stop processing any further rewrite rules if this rule matches. This ensures no other rules are applied after this one if it matches the request.

Now that we have resolved URL mapping for incoming requests, we still need to provide short and user-friendly URLs in our output HTML, when we link to other internal pages. We may again use the Sling's Resource Resolver API like in the previous example, but in that case, we need to add the Sling Mapping configuration per domain. As this may seem like an overcomplication, we can create a simple, custom Java method to map AEM paths to short URLs. Note that with this solution we get relative URLs not containing the domain, which is also slightly better for SEO.

// For path /content/meticulous/com/uk/en returns /uk/en
public static String getShortUrl(String aemPath) {
    final String[] segments = aemPath.split("/");
    return aemPath.startsWith("/content") && segments.length > 3
         ? "/" + String.join("/", Arrays.copyOfRange(segments, 3, segments.length))
         : aemPath;
}

Comparison

Now that we've seen both examples, let's compare the two approaches and list down the consequences of choosing Sling Mappings vs Dispatcher Rewrites for URL shortening.

Sling Mappings, as a server-side URL management solution, ensures consistent behavior across environments. This approach is integrated well with AEM’s repository and Resource Resolver. Also, it supports reverse mapping for generating friendly URLs in links. Mappings are quite flexible for handling highly dynamic content. On the other hand, it may require complex configurations for large-scale, multi-site, multi-domain projects. It also brings limited performance benefits compared to Dispatcher Rewrites.

Dispatcher Rewrites, as a web server URL management solution, is both lightweight and efficient. This approach is easier to configure and manage for static and predefined URL patterns. One additional benefit may be that there is no dependency on AEM’s internal configurations. On the other hand, it requires a bit of know-how in web server configurations. Also, it does not support reverse mapping natively, so it needs to be handled in the AEM.

The last thing worth mentioning is vanity URL handling in a multi-domain setup. As AEM does not natively support reusing the same vanity URL across different sites and domains, a custom solution like this one needs to be applied. However, this solution will only work if you use Dispatcher Rewrites for URL shortening so AEM receives a request with a full page path.

Conclusion

Both Sling Mappings and Dispatcher Rewrites are powerful tools for URL shortening and mapping in AEM. While Sling Mappings excels in flexibility and integration with AEM’s resource resolver, Dispatcher Rewrites provides a simple solution with better performance for static mappings. The choice ultimately depends on your project’s requirements, including URL dynamics, performance needs, and ease of maintenance. By choosing the right solution wisely, we can deliver user-friendly URLs and efficient URL management in our AEM applications.

In case you are not sure which solution is the best choice for your project, my personal favorite is Dispatcher Rewrites. As this solution is simpler to set up and maintain, it is usually a better choice for simple URL shortening use cases. This is especially true if the AEM server doesn't need to be aware of the domain configuration. Also, receiving a full path to every resource will make debugging AEM requests easier.

Filed underAEMCMSSEO
All posts

Blog

All posts

If these challenges sound familiar, explore how we help enterprises reduce risk.