I recently ran into a situation on a project where I needed to redirect certain URLs to a different Sitecore location.
I knew I wanted to keep the URL as it was but I needed it to serve different Sitecore content. I also didn't want to make a client side redirect, so I did some digging on the web I was able to find the solution: create a server side redirect.
To do this in Sitecore, we need to modify the HttpRequestBegin pipeline processors. The processor that we need to override is: Sitecore.Pipelines.HttpRequest.ExecuteRequest.
<processor type="Sitecore.Pipelines.HttpRequest.ExecuteRequest, Sitecore.Kernel"/>
Now let’s move onto the code:
- Create a class that inherits Sitecore.Pipelones.HttpRequest.ExecuteRequest
- Override method void PerformRedirect(string URL)
Inside this method, we need to check if the configuration of UseServerSideRedirect is set to “true”. You can set this property in the configuration file. Look in the configuration file at the "RequestErrors.UseServerSideRedirect" value; by default it is “false”, change the value to “true”.
Next, we need to make sure that the code is retrieving the original URL. Currently, this method is retrieving the 404 page. Then, using the original URL, we proceed to check if it’s the URL we are expecting to convert, or if it is just a normal 404.
Now, all the magic happens in the GetItemFromUrl method. Let’s analyze it:
This method receives a URL. Extracting and replacing particular pieces of it, we can convert it into the Sitecore path to the actual item that we need (or you can replace by an item for default, this is usually the case of a 404 item).
After we get the real Sitecore path to the item, you just access the database and retrieve it.
Returning to the PerformRedirect method, now you replace the current HTTPContext with the context we just fetched.
That’s all there is to it. Have you tried a server side redirect on your Sitecore site? Let me know in the comments section below.
Some information from this post was gathered from the Victor Feinman blog (http://www.victorfeinman.com/).