How to Remove # from URL in Angular
Ever wondered why your AngularJS app’s URLs include a #
symbol? It might seem unnecessary, but it can negatively impact both user experience and SEO. The good news is you can remove it and make your URLs clean, professional, and SEO-friendly.
This guide will walk you through the exact steps to remove # from URL in Angular, ensuring a seamless routing experience for your Single Page Application (SPA). Let’s get started!
Why Remove # from URL in Angular?
The #
in AngularJS URLs is added by default when using ngRoute
for routing. While it helps with routing configurations, it can:
- Make URLs look unprofessional.
- Create issues with search engine optimization (SEO).
- Cause confusion for users when sharing URLs.
By removing the #
, you create clean URLs that improve both functionality and presentation.
Step-by-Step Guide to Remove # from URL in Angular
Step – 1 Configure
.config([‘$routeProvider’, ‘$locationProvider’, function ($routeProvider, $locationProvider) {
$routeProvider
.when(‘/’, {
templateUrl: ‘views/login.html’,
controller: ‘loginCtrl’
})
.when(‘/main’, {
templateUrl: ‘views/main.html’,
controller: ‘mainCtrl’
})
.otherwise({
redirectTo: ‘/’
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}]);
Step 2: Set Base for Relative Links
HTML5 mode requires a <base>
tag in your HTML file. Add the following tag inside the <head>
section:
<base href=”/” />
This ensures the application knows the base path for all relative URLs.
Step 3: Replace href="#"
with href="/"
Replace all instances of href="#"
with proper paths like href="/"
to align with the new routing logic.
Step 4: Server-Side Configuration for Apache
Make changes to the Apache server to support clean URLs. Update the .htaccess
file with the following configuration:
<VirtualHost *:80>
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ – [L]
RewriteRule ^ /index.html
</VirtualHost>
This setup ensures proper URL routinhttps://doyenhub.com/angularjs-development/g and prevents 404 errors.
Conclusion
By following these four simple steps, you can remove #
from URL in AngularJS and create clean, SEO-friendly URLs. This small change will enhance your SPA’s user experience and SEO performance. If you’re using Nginx, contact us for the configuration steps.