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

时间:2015-09-15 19:06:59

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

我正在尝试构建一个使用HTML5应用缓存的单页应用,它会为每个不同的网址缓存全新版本的应用,因此我必须将所有人重定向到/并拥有我的app之后路由它们(这是devdocs.io上使用的解决方案)。

这是我的nginx配置。我希望所有请求都发送文件(如果存在),重定向到/auth/api的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;
}

1 个答案:

答案 0 :(得分:22)

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

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

/index.html