【问题标题】:Nginx config for single page app with HTML5 App Cache带有 HTML5 应用缓存的单页应用的 Nginx 配置
【发布时间】:2015-12-12 03:54:37
【问题描述】:

我正在尝试构建一个使用 HTML5 App Cache 的单页应用程序,该应用程序将为每个不同的 URL 缓存一个全新版本的应用程序,因此我必须将每个人重定向到 / 并让我的应用程序随后路由它们(这是devdocs.io上使用的解决方案)。

这是我的 nginx 配置。我希望所有请求都发送文件(如果存在),重定向到我的 API /auth/api,并将所有其他请求重定向到 index.html。为什么以下配置会导致我的浏览器说存在重定向循环?如果用户点击位置块 #2 并且他的路线与静态文件不匹配,他将被发送到位置块 #3,这会将他重定向到“/”,它应该点击位置块 #1 并提供 index.html,对吗?是什么导致了这里的重定向循环?有没有更好的方法来做到这一点?

root /files/whatever/public;
index index.html;

# If the location is exactly "/", send index.html.
location = / {
    try_files $uri /index.html;
}

location / {
    try_files $uri @redirectToIndex;
}

# Set the cookie of the initialPath and redirect to "/".
location @redirectToIndex {
    add_header Set-Cookie "initialPath=$request_uri; path=/";
    return 302 $scheme://$host/;
}

# Proxy requests to "/auth" and "/api" to the server.
location ~* (^\/auth)|(^\/api) {
    proxy_pass http://application_upstream;
    proxy_redirect off;
}

【问题讨论】:

  • 你有root 指令和index.html 文件吗?检查error.log
  • 是的。已更新问题以包含它。
  • 我的错误日志中没有任何内容。
  • 您是否与curl(或wget)核对过?可能是你的浏览器缓存了错误的重定向……
  • curl 给了我一些 nginx HTML <center><h1>302 Found</h1></center><hr><center>nginx/1.8.0</center>wget 说“超过 20 个重定向”。这里没有缓存问题。

标签: redirect nginx single-page-application html5-appcache


【解决方案1】:

该循环消息表明 /files/whatever/public/index.html 不存在,因此位置 / 中的 try_files 在等于 /index.html 时找不到 $uri,因此 try_files 始终在内部重定向那些请求执行外部重定向的@位置。

除非您的设置比您概述的更复杂,否则我认为您不需要做这么多。您不需要为单文件 js 应用程序发送外部重定向(甚至内部重定向)或服务器端 cookie。 app 和 api 的正则表达式匹配也不完全正确。

root /files/whatever/public;
index index.html;

location / {
    try_files $uri /index.html =404;
}

# Proxy requests to "/auth" and "/api" to the server.
location ~ ^/(auth|api) {
    proxy_pass http://application_upstream;
    proxy_redirect off;
}

【讨论】:

  • 谢谢,原来 index.html 不存在。我很好奇你为什么说我不需要服务器端 cookie 发送或重定向? HTML5 App Cache 会不希望地为每个 URL 保存一个全新的缓存,所以我看到的唯一解决方案是我需要设置 cookie,将所有请求重定向到 /,然后在前端的 JavaScript 中重新路由它们。跨度>
  • 你能用 slugs 代替虚拟 url 吗?而不是http://site/path1/path2/foohttp://site/#path1/path2/foo。这是我能想到的避免重复 html5 应用程序缓存或极其低效的外部重定向的唯一方法。
猜你喜欢
  • 1970-01-01
  • 2018-03-04
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-17
  • 2012-03-06
相关资源
最近更新 更多