Search code examples
javascripthtmlnginxhtml5-history

Window.history API - 404 Because I am on URL /


I am learning to use window.history.pushState.

I have three links:

 <a href="/">Home</a>
 <a href="/skills">Skills</a>
 <a href="/experiences">Experiences</a>

Here's my code:

(function() {
function loadHtml(url, cb) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            cb(this.responseText);
        }
    };
    xhttp.open("GET", url, true);
    xhttp.send();
}

function setHrefEvents() {
    var links = document.getElementsByClassName('menu')[0].getElementsByTagName('li');

    for (i = 0; i < links.length; i++) {
        links[i].getElementsByTagName('a')[0].addEventListener('click', function(e) {
            e.preventDefault();
            window.history.pushState({
                    urlPath: 'views/' + (e.target.pathname.match(/\/([a-z]*)/)[1] || 'home') + '.html'
                },
                e.target.pathname.match(/\/([a-z]*)/)[1], e.target.pathname);
            loadHtml(window.history.state.urlPath, function(html) {
                document.getElementsByTagName('main')[0].innerHTML = html;
            });
        });
    }
}

function setUrl() {
    window.history.pushState({
        urlPath: 'views/' + (window.location.pathname === '/' ? 'home' : window.location.pathname) + '.html'
    }, 'Title', window.location.pathname);
    loadHtml(window.history.state.urlPath, function(html) {
        document.getElementsByTagName('main')[0].innerHTML = html;
    });
    return;
}

function setFooter() {
    document.getElementsByClassName('footer-date')[0].innerHTML = new Date().getFullYear();
}

setFooter();
setUrl();
setHrefEvents();
})();

When I click on a link, the history state is well pushed and my content correctly loaded. But when I reload the page on localhost/skills for exemple, I have 404.

My question is, how can I manage to not have a 404 localhost/skills?

I don't know if it can help, but I running my website on a nginx server. There is obviolously something I missed and I don't know what.

Thanks for your help!


Solution

  • I found my solution !

    It is about the configuration of my web server.

    Here : https://gist.github.com/aotimme/5006831

    This is the working configuration for nginx + JavaScript History API.

    Hope it will help !