In this article, I'll share the CQ component for URL redirect that I did. How it works is that, the component provide content author additional functionality to set redirect message. If redirect message is set, the component will redirect user to a new location via JavaScript (the JavaScript function has an interval/delay).

 

Component's JSP file:

<%@include file="/path/to/your/project/global.jsp"%>
<%@page import="org.apache.sling.settings.SlingSettingsService"%><% String redirectUrl = properties.get("redirectUrl", ""); String redirectMsg = properties.get("redirectMsg", ""); String redirectDelay = properties.get("redirectDelay", "100"); if (redirectUrl.length() > 0) { if (!redirectUrl.equals("/")) { redirectUrl = redirectUrl + (redirectUrl.contains("/content/") && !redirectUrl.contains(".html") ? ".html" : ""); } if (redirectMsg.length() > 0) { out.print(redirectMsg); %><script> setTimeout(function() {window.location="<%= redirectUrl %>"}, <%= redirectDelay %>); </script><% } else { // location is the 'page to redirect to' if (!redirectUrl.equals(currentPage.getPath())) { // ON PUBLISH INSTANCE, SET 301 REDIRECT CODE try { SlingSettingsService slingSettings = sling.getService(SlingSettingsService.class); if (slingSettings.getRunModes().contains("publish")) { response.setStatus(301); response.setHeader("Location", redirectUrl); response.setHeader("Connection", "close"); return; } } catch (Exception e) { // Do nothing, just try with a 302. } // ON AUTHOR INSTANCE response.sendRedirect(redirectUrl); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } } else { %>Setup redirect.<% } %>

Component's XML file for CQ Dialog:

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
    jcr:primaryType="cq:Dialog"
    helpPath="en/cq/current/wcm/default_components.html#Title"
    title="Redirect"
    xtype="panel">
    <items jcr:primaryType="cq:WidgetCollection">
        <redirectUrl
            jcr:primaryType="cq:Widget"
            fieldLabel="Title"
            name="./redirectUrl"
            xtype="pathfield"/>
        <redirectMsg
            jcr:primaryType="cq:Widget"
            fieldLabel="Redirect message"
            grow="{Boolean}true"
            name="./redirectMsg"
            xtype="textarea"/>
        <redirectDelay
            jcr:primaryType="cq:Widget"
            defaultValue="1000"
            fieldLabel="Redirect delay"
            name="./redirectDelay"
            value="1000"
            xtype="textfield"/>
    </items>
</jcr:root>

 

Hope you find it useful. All comments are welcome.