AngularJS routing without the hash '#'

前端 未结 10 775
野性不改
野性不改 2020-11-22 01:40

I\'m learning AngularJS and there\'s one thing that really annoys me.

I use $routeProvider to declare routing rules for my application:

         


        
相关标签:
10条回答
  • 2020-11-22 01:57

    Using HTML5 mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html). Requiring a <base> tag is also important for this case, as it allows AngularJS to differentiate between the part of the url that is the application base and the path that should be handled by the application. For more information, see AngularJS Developer Guide - Using $location HTML5 mode Server Side.


    Update

    How to: Configure your server to work with html5Mode1

    When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites. Here are some examples:

    Apache Rewrites

    <VirtualHost *:80>
        ServerName my-app
    
        DocumentRoot /path/to/app
    
        <Directory /path/to/app>
            RewriteEngine on
    
            # Don't rewrite files or directories
            RewriteCond %{REQUEST_FILENAME} -f [OR]
            RewriteCond %{REQUEST_FILENAME} -d
            RewriteRule ^ - [L]
    
            # Rewrite everything else to index.html to allow html5 state links
            RewriteRule ^ index.html [L]
        </Directory>
    </VirtualHost>
    

    Nginx Rewrites

    server {
        server_name my-app;
    
        index index.html;
    
        root /path/to/app;
    
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
    

    Azure IIS Rewrites

    <system.webServer>
      <rewrite>
        <rules> 
          <rule name="Main Rule" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="/" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
    

    Express Rewrites

    var express = require('express');
    var app = express();
    
    app.use('/js', express.static(__dirname + '/js'));
    app.use('/dist', express.static(__dirname + '/../dist'));
    app.use('/css', express.static(__dirname + '/css'));
    app.use('/partials', express.static(__dirname + '/partials'));
    
    app.all('/*', function(req, res, next) {
        // Just send the index.html for other files to support HTML5Mode
        res.sendFile('index.html', { root: __dirname });
    });
    
    app.listen(3006); //the port you want to use
    

    See also

    • Advantages/Disadvantages of HTML5 mode vs Hash mode AngularJS
    • AngularJS - How to turn off hashbang mode
    0 讨论(0)
  • 2020-11-22 01:59

    try

    $locationProvider.html5Mode(true)
    

    More info at $locationProvider
    Using $location

    0 讨论(0)
  • 2020-11-22 02:03

    **

    It is recommended to use the HTML 5 style (PathLocationStrategy) as location strategy in Angular

    ** Because

    1. It produces the clean and SEO Friendly URLs that are easier for users to understand and remember.
    2. You can take advantage of the server-side rendering, which will make our application load faster, by rendering the pages in the server first before delivering it the client.

    Use Hashlocationstrtegy only if you have to support the older browsers.

    Click here to know more

    0 讨论(0)
  • 2020-11-22 02:05

    In Angular 6, with your router you can use:

    RouterModule.forRoot(routes, { useHash: false })
    
    0 讨论(0)
  • 2020-11-22 02:06

    In fact you need the # (hashtag) for non HTML5 browsers.

    Otherwise they will just do an HTTP call to the server at the mentioned href. The # is an old browser shortcircuit which doesn't fire the request, which allows many js frameworks to build their own clientside rerouting on top of that.

    You can use $locationProvider.html5Mode(true) to tell angular to use HTML5 strategy if available.

    Here the list of browser that support HTML5 strategy: http://caniuse.com/#feat=history

    0 讨论(0)
  • 2020-11-22 02:14

    If you enabled html5mode as others have said, and create an .htaccess file with the following contents (adjust for your needs):

    RewriteEngine   On
    RewriteBase     /
    RewriteCond     %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
    RewriteCond     %{REQUEST_FILENAME} !-f
    RewriteCond     %{REQUEST_FILENAME} !-d
    RewriteRule     ./index.html [L]
    

    Users will be directed to the your app when they enter a proper route, and your app will read the route and bring them to the correct "page" within it.

    EDIT: Just make sure not to have any file or directory names conflict with your routes.

    0 讨论(0)
提交回复
热议问题