AngularJS and Page Refresh

I’ve been building out a recent project, Jazzleadsheets.com, on AngularJS and Magento being served by Nginx, and ran into a frustrating problem. When I refreshed any page other than the index, the site would throw a 500 Internal Server Error. Additionally, if I entered in a nonsense URL, which should be directed back to the homepage, I received the same 500 error. I was stumped.

After fruitless hours researching and testing, I made a breakthrough. I realized that in my application config I implemented “HTML5 Mode” with:

.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
}])

This allowed me to dump the hash-bang syntax (example.com/#/catalog) and present the user with well-formatted URLs (example.com/catalog). This was also the root of the issue. Commenting out the code segment above resulted in hash-bang URLs, but allowed me to refresh any page correctly as AngularJS knew how to route those. From there I put the pieces together and realized that Nginx was configured correctly to route the requests for AngularJS. The answer lie in a single addition to my Nginx location block:

location / {  
    ...
    try_files $uri /example.html;
    ...
}

Where example.html is replaced by the base file you want to route requests to. In my case, index.html. With this addition and a quick restart of Nginx, my page refreshes worked like a boss.

Photo by NASA at Unsplash