具有 HTML5 应用程序缓存的单页应用程序的 Nginx 配置

Nginx config for single page app with HTML5 App Cache

我正在尝试构建一个利用 HTML5 应用程序缓存的单页应用程序,它将为每个不同的 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;
}

该循环消息表明 /files/whatever/public/index.html 不存在,因此位置 / 中的 try_files 在等于 [=11= 时找不到 $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;
}