javascript - 如何使用动态 url (slugs) 和 ng-include 在 Angular JS 中正确返回 404?

标签 javascript angularjs .htaccess angular-ui-router

我目前正在使用 UI-router 使用 AngularJS 为我们公司构建一个投资组合网站。我们使用 HTML5 url 方案,并且我已经准备好标准 .htaccess 来重写对 index.html 的请求(尽管在生产中这将在 .NET 服务器上运行)。

网站的某些部分由通过 ng-include 指令呈现的自由格式 html 文档组成,以允许我们的开发人员和设计人员最大程度地自由地创建他们想要的某些页面 - 例如,可能需要完全不同的布局的客户案例研究和媒体。

页面都是通过 slug 参数加载到某种状态,例如“/work/some-case-study-name”。然后状态处理程序获取 slug 参数并将其作为 url 提供给 html 文件以供 ng-include 加载。例如,上面的 url 将解析为“/partials/case-studies/some-case-study-name.html”。这全部加载到指令中。

目前,似乎不可能捕获输入错误的 slug url。看来,无论是通过 .htaccess 设置还是 Angular 的路由系统,当 ng-include 找不到请求的 html 文件时,它总是返回 200OK 并且只渲染站点的路由。

有谁知道如何让 ng-include 在尝试加载的文档不存在时返回 404 吗?

谢谢!

最佳答案

我不太擅长 .htaccess 重写配置,但在尝试了几个示例之后,这是我能找到的唯一一个能够可靠地返回 404 的资源,而这些资源在 Angular html5 设置中确实不存在:

http://ericduran.io/2013/05/31/angular-html5Mode-with-yeoman/

具体:

# Apache .htaccess

# angularjs pushstate (history) support:
# See http://www.josscrowcroft.com/2012/code/htaccess-for-html5-history-pushstate-url-routing/
<ifModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
    RewriteCond %{REQUEST_URI} !.*\.(css|js|html|png) #Add extra extensions needed.
    RewriteRule (.*) index.html [L]
</ifModule>

这与其他(包括 Angular 站点上的官方示例)之间的区别似乎是匹配特定文件扩展名的规则。有了这个,当我尝试通过 ng-include 加载不存在的文件时,我得到了 404,这正是我所追求的。

编辑:

另外 - 对于 .NET 爱好者,这里是等效的 web.config:

<?xml version="1.0"?>
<configuration>
  <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" />
            <add input="{REQUEST_URI}" pattern=".*\.(css|js|html|png|jpg)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

关于javascript - 如何使用动态 url (slugs) 和 ng-include 在 Angular JS 中正确返回 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24975514/

相关文章:

javascript, jQuery - 检查数组中是否存在值

javascript - 如何运行使用 jquery.load() 加载的页面中包含的 javascript 代码

javascript - 如何在 Django 模板中为标签创建动态 ID

angularjs - ionic 自定义模态动画

.htaccess - "deny from all"带有自定义消息?

javascript - 在删除之前取消绑定(bind)元素的事件是否有任何性能提升或必要性?

javascript - 在 Angular JS 中从子文档 Controller 分配父文档按钮单击事件

javascript - Angularjs 在 ng-repeat 两项中对数据进行排序

.htaccess - 以编程方式在 MAMP Pro 上针对特定页面强制使用 https(不是站点范围且不使用 .htaccess)

apache - 使用 htaccess 的域特定机器人文件将 robots.txt 重写为 example.com.txt 或回退到 default.txt