nginx:将所有请求发送到单个html页面

时间:2011-08-11 14:27:11

标签: javascript nginx history

使用nginx,我想保留网址,但无论如何都会加载相同的网页。我将使用History.getState()的网址在我的javascript应用中路由请求。这似乎应该是一件简单的事情吗?

location / {
    rewrite (.*) base.html break;
}

有效但重定向网址?我仍然需要网址,我只想总是使用同一页面。

6 个答案:

答案 0 :(得分:173)

我认为这会为你做到:

location / {
    try_files /base.html =404;
}

答案 1 :(得分:22)

仅使用try_files对我无效 - 它导致我的日志中出现重写或内部重定向周期错误。

Nginx文档还有一些其他细节:

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

所以我最终使用了以下内容:

root /var/www/mysite;

location / {
    try_files $uri /base.html;
}

location = /base.html {
    expires 30s;
}

答案 2 :(得分:15)

你的原始重写几乎可以正常工作。我不确定为什么它会重定向,但我认为你真正想要的只是

rewrite ^ /base.html break;

您应该可以将其放在某个位置或直接放在服务器中。

答案 3 :(得分:11)

这对我有用:

location / {
    alias /path/to/my/indexfile/;
    try_files $uri /index.html;
}

这使我能够为javascript单页应用创建一个包罗万象的URL。如果它们与npm run build位于同一目录中,则会找到index.html构建的所有静态文件,如css,fonts和javascript。

如果静态文件位于另一个目录中,由于某种原因,您还需要以下内容:

# Static pages generated by "npm run build"
location ~ ^/css/|^/fonts/|^/semantic/|^/static/ {
    alias /path/to/my/staticfiles/;
}

答案 4 :(得分:7)

正确的方法是:

location / {
    rewrite (.*) base.html last;
}

使用last将使nginx根据重写结果找到新的location块。

try_files也是解决此问题的绝佳方法。

答案 5 :(得分:4)

这对我有用:

location / {
    try_files $uri $uri/ /base.html;
}