0

I'm trying to fix the issue using $locationProvider.html5Mode(true); when refreshing the page.

It fixes this localhost/#/home hash in urls, but when I refresh the page it shows a 404.

I'm using nginx local.

Running angularjs v1.0.7. Latest versions don't work apparently.

Header

<base href="/">

Angular

var app = angular.module('myApp', []);

app.config(function($routeProvider, $locationProvider) {
      $routeProvider
      .when('/', {
        templateUrl: 'home.html',
        title: 'home'
      })
      .when('/about', {
        templateUrl: 'about.html',
        title: 'about'
      })
      .when('/contact', {
        templateUrl: 'contact.html',
        title: 'contact'
      })
      .otherwise({
        redirectTo: '/'
      });
      $locationProvider.html5Mode(true);
    });

1 Answer 1

0

When you use Html5 mode your links became from http://example.com/#about to http://example.com/about but there's one thing why you recieve 404 - what server side solution do you use? As your 404 is returned by your backend rather than by angularJS router itself as in order to make it accessible in html5 mode you need to provide same html page with js included to your new routes on server side just as you've supplied to your home page loading your angular application. For example in Laravel imagine you have such route for your site root, and your angular app code is in home.blade.php

    Route::get('/',function(){ return view('home');});

so you need to create same routes pointing to the same view in order to load your angular js app with markup then your angular router will properly show you your needed template based on routing view.

   Route::get('/about',function(){ return view('home');});
   Route::get('/contact',function(){ return view('home');});

If your use different server side framework or solution hope you've got main idea of what you need to do to solve 404 problem when accessing directly - just set up same routes on server side pointing to homepage loading your angular js app. If you dont use any server side framework serving static html file by nginx you need to set up /contacts /about locations to point to your document root index.html which contains your angular App.

for expample

location / {
    root   /srv/www/example.com/public_html;
    index  index.html index.htm;
}
location /about/ {
    root   /srv/www/example.com/public_html;
    index  index.html index.htm;
}
location /contacts/ {
    root   /srv/www/example.com/public_html;
    index  index.html index.htm;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.