刷新页面显示"找不到页面"

45 angularjs

我有一个应用程序,它使用单个ng视图和多个控制器和视图.如果我浏览根目录,例如:www.domain.com,一切正常.除非我按下Ctrl + R(刷新),否则它会给我404错误页面找不到.例如:在此页面刷新给我错误. http://domain.com/item/1/.

但是,如果我使用hashbang访问该页面,那么它将起作用.eg:http://domain.com/#!/ item1 /

我该如何解决这个问题?我的htacess是空的.我使用chrome支持html5 hashbang.

Pas*_*Kit 49

当浏览器调用时http://example.com/#!/item/1/,它正在调用索引页面http://example.com/,然后您的JS通过分析主题标签来确定要显示的内容.

当浏览器调用时http://example.com/item/1/,您的服务器正在尝试提供http://example.com/item/1/它找不到的索引页面,因此会抛出404错误.

要达到你想要的效果,你需要:

  • 创建重写规则以重写指向根索引页的链接
  • 调整你的JS,使它生成hashtag而不是URL.如果您使用的是AngularJS $locationProvider.html5Mode(false);,请使用或关闭html5模式
  • 把一个索引页面http://example.com/item/1/重定向到http://example.com/#!/item/1/- 但请注意,这需要为每个/ prettyPath /你克里特重复.

假设您使用的是Apache并且索引文件是index.html,请尝试将以下内容添加到.htaccess文件中,以便在尝试其他两个解决方案之前创建重写规则.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)       /index.html/#/$1 
</IfModule>
Run Code Online (Sandbox Code Playgroud)

如果您使用的是没有服务器端逻辑的纯AngularJS/Ajax解决方案,请将index.php更改为index.html(或index.htm,具体取决于您的根索引文件名).


Muh*_*eem 18

您只需在.htaccess中添加以下脚本即可

RewriteEngine On 
Options FollowSymLinks

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]
Run Code Online (Sandbox Code Playgroud)

  • @Shri&Athi您确定mod_rewrite已启用吗?在Debian/Ubuntu下,使用`sudo a2enmod rewrite`.如果它输出"mod rewrite already enabled",实际上它"不起作用",但是如果输出类似于"现在启用了Mod重写",那么它可能是您期望的修复.我想需要重新启动apache.(`sudo service apache2 restart`) (2认同)

use*_*080 12

这是URL重写(IIS)的.NET版本

<system.webServer>
    <rewrite>
      <!--This directive was not converted because it is not supported by IIS: RewriteBase /.-->
      <rules>
        <rule name="Imported Rule 1" stopProcessing="true">
          <match url="^index\.html" ignoreCase="false" />
          <action type="None" />
        </rule>
        <rule name="Imported Rule 2" stopProcessing="true">
          <match url="." ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
Run Code Online (Sandbox Code Playgroud)