How to add a custom 404 page on your Tumblr

Redirect to a custom 404 page

  1. Go to your blog configurations on Edit Appearance, then click on Edit Theme
  2. then click on Edit HTML button
  3. Use CMD+F or CTRL+F to localize the </head> tag and insert the following code right before it.

Copy this code

<!-- Custom 404 Redirect -->
<script>
/** Detect the Not Found page on Tumblr and redirect to a custom /404 page */
(function(fn){var d=document; (d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();})(function(){
    if((/^\s*Not Found\s*$/i).test((document.querySelector('h2')||"").innerText)){
        var l = location, enc = encodeURIComponent;
        l.replace([l.protocol,"//",l.host,"/404","?source=",enc(l.pathname+l.search+l.hash),"&refer=",enc(l.origin)].join(''));
    }
});
</script>

Paste it before the head closing tag

(paste right here)</head>
  1. Hit Save

image

Adding code to your blog theme


Creating your custom 404 page

  1. On the Edit Theme page
  2. Click “Add a page”
  3. Use the url yourblogurl/404
  4. You can use Standard Layout or Custom Layout
  5. Craft your custom page as desired

If you want to add dynamic links like, the page the visitor was tryng to reach, and the page that sent him to the broken link. I also made a script that you can use on your custom 404 page.

The broken URL

<span class="source">{{this.source}}</span>

Link to the refer page

<a class="dynamic source" href="{{this.refer}}">{{this.refer}}</a>

Then add this script to your 404 page

<script type="text/javascript">//<![CDATA[
function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

function eachElm(selector, fn){
    var elements = document.querySelectorAll(selector);
    Array.prototype.forEach.call(elements, fn);
}

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}

ready(function(){

    eachElm(".dynamic.source", function(elm){
        elm.href = getURLParameter("source");
        elm.innerHTML = getURLParameter("source");
    });

    eachElm(".dynamic.refer", function(elm){
        elm.href = getURLParameter("refer");
        elm.innerHTML = getURLParameter("refer");
    });

});
//]]>
</script>

November 23rd, 2015 2:26pm Tumblr Hacks Javascript