【问题标题】:Angular Nginx Docker 404角 Nginx 码头工人 404
【发布时间】:2019-10-12 13:23:31
【问题描述】:

一直在让自己发疯,试图弄清楚这一点。

我有一个非常简单的带有路由的 Angular 项目,下面是 app.module.ts、nginx.conf 和 docker 文件。

我通过容器启动

docker run --rm -d -p 80:80/tcp demo:latest

浏览到http://localhost,网站可以渲染所有路由

如果我在 http://localhost/contact 并刷新页面或直接输入 Url,我会从 Nginx 得到 404。

nginx.conf 中有 try_files $uri /index.html;这是所有有类似问题的帖子都说需要设置的。

知道我做错了什么。

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ContactComponent } from './contact/contact.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'about', component: AboutComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

nginx.conf

server {
    listen   80;

    root /usr/share/nginx/html;
    index index.html;

    server_name _;

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

码头文件

FROM nginx

COPY nginx.conf /etc/nginx/conf.d/

RUN rm -rf /usr/share/nginx/html/*

COPY ./dist /usr/share/nginx/html

【问题讨论】:

    标签: angular docker nginx http-status-code-404


    【解决方案1】:

    愚蠢的我,我没有覆盖 docker 文件中的默认 docker conf

    COPY nginx.conf /etc/nginx/conf.d/default.conf
    

    【讨论】:

    • 谢谢,这对我帮助很大!
    • 谢谢迈克!感谢您的帖子,我注意到 nginx 中有另一个配置文件!我修改了一个,路由对我来说工作正常
    • 非常感谢!这是我第一次使用 docker 创建镜像并运行它,这对我来说真的很有效
    【解决方案2】:

    AppRoutingModule 中使用{ "useHash" : true }

    imports: [RouterModule.forRoot(routes , {useHash : true } )]
    

    当你输入34.**.**.**:8080/anyroute 时,Nginx 将搜索他的服务器中可用的路由,而不是 Angular 应用程序。这就是发生 404 错误的原因。使用 useHash true ,它会自动使用哈希格式化您的网址。

    34.**.**.**:8080/#/anyroute
    

    # 之后 Nginx 将无法读取 它将重定向到您的应用

    【讨论】:

      猜你喜欢
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 2017-02-01
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      相关资源
      最近更新 更多