AngularUI路由URL始终显示/#/home及去除哈希符号问题咨询
Problem 1: ui-sref links aren't updating the URL to /forum
It sounds like either your state configuration is off, or you're using the wrong value in ui-sref. Let's walk through the fixes step by step:
Double-check your state definition
Make sure yourforumstate is configured with the correcturlproperty in$stateProvider:angular.module('yourApp', ['ui.router']) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/home', templateUrl: 'home.html' }) .state('forum', { url: '/forum', // This line must be set correctly templateUrl: 'forum.html' }); // Default route (if you need one) $urlRouterProvider.otherwise('/home'); });Verify your ui-sref usage
Theui-srefdirective uses the state name (not the template filename or raw URL path). Your link should look like this:<a ui-sref="forum">Go to Forum</a>If you accidentally used
ui-sref="home"orui-sref="forum.html", that's why it's stuck on/home.Rule out caching or unexpected redirects
Clear your browser cache or do a hard refresh (Ctrl+F5) to eliminate cached old configurations. Also, check if you have any custom$stateChangeStartlisteners that might be forcing a redirect back to the home state.
Problem 2: Removing the hash (#) from URLs
To get rid of the hash, you'll need to enable AngularJS's HTML5 Mode. Here's what to do:
Update your app's config
Inject$locationProviderinto your config block and enablehtml5Mode:angular.module('yourApp', ['ui.router']) .config(function($stateProvider, $urlRouterProvider, $locationProvider) { // Your existing state configs go here... // Turn on HTML5 mode $locationProvider.html5Mode(true); // Optional: Remove the default hash prefix (!) if you had it enabled before $locationProvider.hashPrefix(''); });Add a base href to your index.html
In the<head>section of your main HTML file, add a<base>tag pointing to your app's root path. This helps AngularJS resolve relative paths correctly:<head> <!-- Other meta tags, styles, etc. --> <base href="/mywebsite/"> </head>Adjust the
hrefvalue to match your app's actual root (use just/if it's hosted at your domain's root).Configure your server (critical step!)
HTML5 Mode relies on your server routing all requests back toindex.html(since AngularJS handles client-side routing). Skip this, and direct links or page refreshes will throw 404 errors.Apache: Create or modify a
.htaccessfile in your app's root:RewriteEngine On RewriteBase /mywebsite/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /mywebsite/index.html [L]Nginx: Add this to your server block:
location /mywebsite/ { try_files $uri $uri/ /mywebsite/index.html; }
After these steps, your URLs will look like mywebsite/home and mywebsite/forum without the hash.
内容的提问来源于stack exchange,提问作者Webdev

