angularjs - .htaccess 用于具有 HTML5 模式的 AngularJS 应用程序的子文件夹

标签 angularjs apache .htaccess mod-rewrite html5mode

概览:

我有一个使用 的 AngularJS 应用程序$locationProvider.html5Mode(true) 它由 Apache 服务器提供。到目前为止,我使用的源代码可以从其他人那里访问,我只需要重定向到 index.html 以获取 angularJS 的 HTML5 模式。所以我为 .htaccess 准备了这个我的文件 /app文件夹。

.htaccess :

<IfModule mod_rewrite.c>

    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]

</IfModule>

修改:

然后我添加了 Grunt 来缩小在 /dist 中生成的整个解决方案。应用程序的文件夹(所以现在可以在/app/dist 找到缩小的解决方案)。我现在想将我的应用程序的全部流量路由到缩小版本,而不让用户更改链接。因此,实际上我想将每个调用从/app 重定向到/app/dist。

现在的目录结构:
app
    dist
        minified versions(css,html,js)

我尝试使用来自 here 的一些条件在/app 的 .htaccess 中,并在/app/dist 中移动了另一个 .htaccess 文件,但没有成功。我什至不知道这两者是否可以以这种方式结合。我知道我可以使用 dist 文件夹作为/app 代替,但我真的不想要这个,因为/app 是一个 repo 并且更容易保持更新。那么我怎样才能通过重定向来实现这一目标呢?

另外,作为第二件事,是否可以以某种方式放置一个标志,以便我让 alpha 用户使用正常(未缩小)版本进行更好的调试?

更新:

我为此添加了一个示例项目 here .我只是保留了上面显示的初始 .htaccess 文件,您可以检查两个版本( /test/test/dist )是否按上述方式工作。此外,它可能有一些未使用的代码和依赖项,但我只是从我的项目中删除了其他部分(不要判断:D)。

为此,我使用了 AngularJS 1.4.8 的初始配置,该配置可能会产生一些错误,例如 herehere .随时将 AngularJS 版本更新到 1.5.8(Angular 1 的最后一个稳定版本),但请考虑 Cosmin Ababei's post 上的评论以及。此外,该项目使用 npm 来安装 grunt(以及 grunt 的其他扩展)、用于 angular 和其他一些基本组件的 bower 以及用于构建缩小版本的 grunt(实际上,它现在只是将资源连接到相同的文件中)。如果您需要更改依赖项,请不要忘记运行 bower install .如果你想重新生成dist文件夹,不要忘记运行npm installgrunt build .

最佳答案

我假设在 /dist 里面您拥有的目录 index.html使用指向缩小资源的更新 URL 和正确的 <base>标签。请注意 <base>标签必须指向 /dist文件夹 - 只是附加 /dist到您用于未压缩 index.html 的值你会没事的。

整理好这些东西后,这里是更新的 .htaccess文件:

RewriteEngine On

# Don't rewrite files
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# If the ALPHA_USER cookie is set, serve the uncompressed files
RewriteCond %{HTTP_COOKIE} ALPHA_USER [NC]
RewriteRule ^ index.html [L]

# Rewrite everything
RewriteRule ^ dist/index.html [L]

你会注意到两件事:
  • 我已删除 RewriteCond %{REQUEST_FILENAME} -d因为很可能您不需要为整个目录提供服务
  • 我添加了 ALPHA_USER cookie,它将用户重定向到未压缩的文件。此 cookie 可以具有您想要的任何值。
  • 关于angularjs - .htaccess 用于具有 HTML5 模式的 AngularJS 应用程序的子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39165096/

    相关文章:

    javascript - 如何修改 Angular 中当前注入(inject)的依赖项列表

    php - 如何根据域默认为另一种语言

    python - 如何将 conda 环境与 mod_wsgi 一起使用?

    apache - 将 *.domain.com 重定向到带有 HTTP 或 HTTPS 前缀的 www.domain.com

    php - 使用 PHP 重写 URL

    javascript - Uncaught ReferenceError : exports is not defined at polyfills. js:17

    angularjs - 如何找到 Ionic 1 项目中使用的 ui-router 版本?

    javascript - 使用 Angular ng-repeat 创建嵌套列表

    apache - 在ElasticSearch中查询列表时未获得预期的输出

    apache - 重定向 https ://www to https://non-www - without seeing certificate error, 可能吗?