AngularJS routing without the hash '#'

前端 未结 10 1054
野性不改
野性不改 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 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

    
        ServerName my-app
    
        DocumentRoot /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]
        
    
    

    Nginx Rewrites

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

    Azure IIS Rewrites

    
      
         
          
            
            
              
              
            
            
          
        
      
    
    

    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

提交回复
热议问题