[英]Angular Nginx Docker 404
一直在努力解決這個問題。
我有一個非常簡單的帶有路由的 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 {}
配置文件
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
在AppRoutingModule
使用{ "useHash" : true }
。
imports: [RouterModule.forRoot(routes , {useHash : true } )]
當您輸入34.**.**.**:8080/anyroute
,Nginx 將搜索在其服務器中可用的路由,而不是在 angular 應用程序中。 這就是為什么會出現 404 錯誤.. 使用 useHash true ,它會自動使用哈希格式化您的 url。
34.**.**.**:8080/#/anyroute
Nginx 將不會讀取#
它會重定向到您的應用程序
傻傻的我,我沒有覆蓋docker文件中的默認docker conf
COPY nginx.conf /etc/nginx/conf.d/default.conf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.