是否可以从angular.js的url中移除#符号?

我仍然希望能够使用浏览器的后退按钮等,当我改变视图,将更新的URL与参数,但我不想要#符号。

教程routeProvider的声明如下:

angular.module('phonecat', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
  when('/phones', {templateUrl: 'partials/phone-list.html',   controller: PhoneListCtrl}).
  when('/phones/:phoneId', {templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl}).
  otherwise({redirectTo: '/phones'});
}]);

我可以编辑这个有相同的功能没有#吗?


当前回答

我的解决方案是创建。htaccess和使用#索里安代码。没有.htaccess,我无法删除#

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]

其他回答

我在web上写了一个规则。在app.js中设置$locationProvider.html5Mode(true)后配置。

霍普,帮助别人。

  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

在index.html中,我将此添加到<head>

<base href="/">

不要忘记在服务器上为iis安装url重写器。

此外,如果你使用Web Api和IIS,这个匹配url将不起作用,因为它将改变你的Api调用。因此,添加第三个输入(第三行条件)并给出一个模式,该模式将排除来自www.yourdomain.com/api的调用

是的,你应该配置$locationProvider并设置html5Mode为true:

angular.module('phonecat', []).
  config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {

    $routeProvider.
      when('/phones', {templateUrl: 'partials/phone-list.html',   controller: PhoneListCtrl}).
      when('/phones/:phoneId', {templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl}).
      otherwise({redirectTo: '/phones'});

    $locationProvider.html5Mode(true);

  }]);

看来现在说这个有点晚了。但是将下面的配置添加到app.module导入中就可以了:

RouterModule.forRoot(routes, { useHash: false })

这个答案假设你正在使用nginx作为反向代理,并且你已经设置了$locationProvider。Html5mode为true。

->献给那些可能还在为上面这些酷东西而挣扎的人。

当然,@maxim grach解决方案工作得很好,但对于如何响应不希望标签被包括在第一个地方的请求的解决方案,可以做的是检查php是否发送404,然后重写url。下面是nginx的代码,

在php位置中,检测404 php错误并重定向到另一个位置,

location ~ \.php${
  ...
  fastcgi_intercept_errors on;
  error_page 404 = /redirect/$request_uri ;
}

然后重写url在重定向位置和proxy_pass数据,当然,把你的网站url在我的博客的url的地方。(请求:只有在你尝试之后才会质疑这个问题)

location /redirect {
  rewrite ^/redirect/(.*) /$1;
  proxy_pass http://www.techromance.com;
}

看看魔法。

这绝对有效,至少对我来说是这样。

根据文档。你可以使用:

$locationProvider.html5Mode(true).hashPrefix('!');

注意:如果您的浏览器不支持HTML 5。别担心:它有 退回到hashbang模式。因此,您不需要检查if(window。history && window.history.pushState){…手动}

例如:如果你点击:<a href="/other">某个URL</a>

在HTML5浏览器: Angular会自动重定向到example.com/other

在非HTML5浏览器中: Angular会自动重定向到example.com/#!/其他