【问题标题】:Properly setting Nginx for handling blocks to handle Angular website正确设置 Nginx 以处理块以处理 Angular 网站
【发布时间】:2019-08-31 23:51:39
【问题描述】:

我在 AWS 实例中使用 Nginx 设置我的 Angular 网站时遇到问题。我的 server.conf 格式如下:

server {
    listen       80;
    server_name  mywebsite.com www.mywebsite.com;

    location /server/ {
        proxy_pass         http://internal-xxxxxxxx-12345678.eu-east-2.elb.amazonaws.com/;
    }

    location / {
        root /home/ubuntu/project/dist/anglr;
        index  index.html index.htm;
    }
}

简而言之,我在一个实例中托管我的 Angular 网站,并且我在另一个实例中托管了一个服务器(由负载平衡器处理)。要访问我的服务器 API,URL 格式为“http://mywebsite.com/server/xxxxx”。当我的 Nginx 收到这个 URL 时,它必须重定向到我的 api-server 实例。我的网站主页运行良好,api-server 也运行良好。

问题是当它必须刷新像“http://mywebsite.com/hobbies”这样的角度页面时,它会抛出 404。

我不明白我的 Nginx conf 文件中缺少什么来处理像“http://mywebsite.com/hobbies”这样的 url

【问题讨论】:

    标签: angular nginx


    【解决方案1】:

    与普通静态文件网站不同,Angular 使用它自己的内部路由。在普通的 Web 服务器中,当用户访问 url 时,例如/category/productA.html,Web 服务器在类别目录下查找并尝试提供 productA.html。

    但是,对于 Angular,当 Web 服务器收到对 /hobbies 的请求时,它会尝试查找目录 /hobbies。但是,Web 服务器找不到它,然后提示它正确抛出 HTTP 404 错误。

    我相信您可以通过更改您的 nginx 配置文件来修复此错误:

    server{
       ...
       root /home/ubuntu/project/dist/anglr;
       ...
    
       location /{
          try_files $uri$args $uri/args/ /index.html
       }
    }
    

    这将提示 nginx 在 404 上再次提供 index.html 文件,并且 Angular 将执行它的内部路由。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 2016-03-19
      • 2019-03-06
      相关资源
      最近更新 更多