Enabling HTML5 mode in AngularJS routing

Loading

Enabling HTML5 mode in AngularJS routing allows you to remove the # (hash) from URLs, making them cleaner and more SEO-friendly. By default, AngularJS uses hashbang URLs (e.g., http://example.com/#/home). Enabling HTML5 mode transforms them into standard URLs (e.g., http://example.com/home).


Step-by-Step Guide to Enabling HTML5 Mode in AngularJS Routing

Step 1: Include AngularJS and ngRoute

Ensure that you have included AngularJS and the ngRoute module in your project.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS HTML5 Mode Routing</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>
</head>
<body ng-app="myApp">
<nav>
<a href="/home">Home</a> |
<a href="/about">About</a> |
<a href="/contact">Contact</a>
</nav>
<div ng-view></div>

<script src="app.js"></script>
</body>
</html>

Step 2: Configure AngularJS Routing

In app.js, configure $routeProvider and enable HTML5 mode in $locationProvider.

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

app.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {
$routeProvider
.when("/home", {
template: "<h1>Welcome to Home</h1>"
})
.when("/about", {
template: "<h1>About Us</h1>"
})
.when("/contact", {
template: "<h1>Contact Us</h1>"
})
.otherwise({
redirectTo: "/home"
});

// Enable HTML5 mode
$locationProvider.html5Mode(true);
}]);

Step 3: Configure the Server

Since AngularJS uses client-side routing, the server needs to redirect all requests to index.html to prevent 404 errors when refreshing the page.

For Apache (.htaccess)

Create a .htaccess file in the root directory:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.html [L]
</IfModule>

For Nginx

Modify the server configuration:

server {
listen 80;
server_name yourdomain.com;
root /var/www/html;
index index.html;

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

For Express.js (Node.js)

Modify the server.js file:

const express = require("express");
const app = express();
const path = require("path");

app.use(express.static(__dirname + "/public"));

app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "/public/index.html"));
});

app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});

Step 4: Testing the Application

  1. Start a local server (if needed).
  2. Open the app in a browser.
  3. Click the navigation links and check the URL.
  4. Refresh the page to ensure the correct routing.

Leave a Reply

Your email address will not be published. Required fields are marked *