A common mistake when setting up multiple redirects for a website is failing to put them in the correct order. Typically, the person setting them up realizes that order is important; but it isn’t always clear how the redirects should be ordered.
Let’s take a look at a simple use case where there are multiple redirects:
Redirect 301 /contact-us /contact
Redirect 301 /our-team /about
Redirect 301 /our-team/john-doe /john-doe
The first redirect can actually live anywhere in the file since there is no competing rule.
However, the other two redirects are competing rules. You can easily find competing rules by finding any redirects where the ‘from’ portion of the path is the same.
In our example, the second redirect will pick up a request for /our-team/john-doe
and send it to /about/john-doe
. Since a redirect triggers immediately once a matching rule is found, our last redirect is never hit.
The Law of Specificity
The Law of Specificity states:
Web redirects should always be ordered by specificity. The most specific redirect rules should always come first and the more general rules should come last.
Let’s reorder our previous example according to this new insight:
Redirect 301 /contact-us /contact
Redirect 301 /our-team/john-doe /john-doe
Redirect 301 /our-team /about
As you can see, now that we’ve placed the more specific rule first, the /our-team/john-doe
request will get forwarded to /john-doe
as expected and any other requests to the /our-team
path will be appropriately redirected within the /about
path.
On a side note, I’ve decided to separate all of my non-competing rules from my competing rules. For competing rules, I like to group them based on their shared ‘from’ path.