如何配置Nginx以使用html5mode [英] How to configure Nginx to work with html5mode

查看:306
本文介绍了如何配置Nginx以使用html5mode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于angularjs中的干净URL,我必须使用$locationProvider.html5Mode(true);,但是刷新页面时会显示404.

For clean urls in angularjs I must use $locationProvider.html5Mode(true); but when I refresh my page it shows a 404.

我已经阅读到我需要配置服务器文件.

I've read that I need to configure server file.

结构

 /html -
 /views -
   home.html
   about.html
   contact.html
 index.html
 app.js

到目前为止我所做的:

nginx.conf

server {
    root /html/views;
    index index.html;

    location / {
    try_files $uri $uri/ =404;
    }
}

推荐答案

Angular HTML5位置模式基本上利用了HTML5历史API来模拟"客户端中的URL更改.但是从服务器的角度来看,URL可能不是真实的(不存在),因此无法在服务器上找到这些页面.通常,有两种解决方案可以让服务器知道URL:

The Angular HTML5 location mode basically took advantage of HTML5 history API to "simulate" URL changes in client. But the URLs are probably not real (not exist) from the point of view from server therefore it's not possible to locate those pages on the server. There are generally two solutions can let server to know the URLs:

  1. 使用服务器端渲染.这被称为ReactJS的另一个框架广泛使用.实际上,AngularJS 2.0也可以在服务器上运行.因此,可以在服务器端生成实际页面并将其提供给客户端.
  2. 使用HTTP服务器重写技术.这就是您要尝试做的.这个想法是将所有相关请求转发到单个AngularJS入口点HTML页面,通常是根目录下的index.html.

对于您的情况,假设AngularJS的入口点是/index.html.试试这个:

For your case, assume the entrypoint of AngularJS is /index.html. Try this:

server {
    root /html/views;
    index index.html;

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

以前的解决方案并不完美,因为它将任意测试每个请求.通过指定更详细的规则,我们可以避免不必要的URL查找:

The previous solution is not perfect, because it will test every request arbitrarily. We can avoid unnecessary URL looking up by specify more detailed rules:

server {
    root /html/views;
    index index.html;

    rewrite "^/users" /index.html last;
    rewrite "^/pages" /index.html last;
    ...
}

使用正则表达式匹配要与Angular一起使用的URL.

Use regular expressions to match the URLs you want to serve with Angular.

这篇关于如何配置Nginx以使用html5mode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆