Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Barry Fogarty 493 posts 1129 karma points
    Aug 25, 2016 @ 09:01
    Barry Fogarty
    0

    IIS rewrite to catch all 'invalid' Umbraco URLs

    I'm trying to create an IIS rewrite rule that will redirect all invalid blog post URLs back to the blog root. The problem is, my rule cannot detect when a URL actually exists, the negate conditions are not matched. I'm guessing because the rewrite rules are processed before Umbraco does any routing. Any ideas how to accomplish this? Can the UrlRewritingNet module handle this scenario? Or, would I be better to write a ContentFinder?

    My web.config rewrite rule:

        <rule name="Blog-Sweeper" stopProcessing="true">
          <match url="^blog/(.*)" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Redirect" url="blog" />
        </rule>
    
  • David Peck 687 posts 1863 karma points c-trib
    Aug 25, 2016 @ 09:49
    David Peck
    0

    You're definitely better using an IContentFinder, as you say your IIS rewrite has no idea what Umbraco content exists or not.

    ContentLastChanceFinderResolver.Current.SetFinder(new My404ContentFinder());
    

    Of course, this will return a piece of content at the requested URL. If you want to get a redirect back to your home page then you'll need to add the redirect to the controller.

  • Barry Fogarty 493 posts 1129 karma points
    Aug 25, 2016 @ 14:30
    Barry Fogarty
    0

    Thanks David. I wanted to return a 301 Redirect rather than a 404 so I went with the content finder as follows, (inserted just before the 404 Handlers) :

    public class BlogNotFoundContentFinder : IContentFinder
        {
            public bool TryFindContent(PublishedContentRequest request)
            {
                // Get the requested URL path + query
                var path = request.Uri.PathAndQuery.ToLower();
    
                if (path.StartsWith("/blog/"))
                {
                    // We only reach this point after normal Umbraco routing has not found content, so
                    // Set the 301 redirect on the request and return
                    request.SetRedirectPermanent("/blog");
                    return true;
                }
    
                return false;
            }
        }
    

    Hope this helps others in a similar situation!

Please Sign in or register to post replies

Write your reply to:

Draft