Angular,Nginx,Docker在页面刷新时导致404错误

时间:2020-04-08 16:13:21

标签: angular docker nginx

我有一个角度应用程序,并在docker容器上使用了nginx。当我运行应用程序时,localhost可以正常工作,并且可以重定向到localhost/auth,但是当我使用地址中的localhost/auth刷新浏览器时,会出现错误404。 我也关注了其他论坛,例如404 Error on page refresh with Angular 7, NGINX and DockerAngular Nginx Docker 404,但是仍然存在相同的问题。

DockerFile

FROM node:alpine as builder

WORKDIR /app
# Install app dependencies
COPY . /app/
RUN cd /app && yarn install
RUN cd /app && yarn build:aot:dev

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

# STEP 2 build a small nginx image with static website
FROM nginx:alpine
COPY ./nginx.conf /etc/nginx/nginx.conf
RUN rm -rf /usr/share/nginx/html/*
COPY --from=builder /app/dist/apps/martor /usr/share/nginx/html
RUN ls /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

nginx.conf

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    gzip  on;

    include /etc/nginx/conf.d/*.conf;
    server {
    listen       80;
    server_name localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    error_page 403 404 /index.html;
    location / {
        root   /usr/share/nginx/html;
        try_files $uri $uri/ index.html;
        index  index.html index.html;


        # Allo CORS
        if ($request_method ~* "(GET|POST|PUT|DELETE|PATCH|OPTIONS)") {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT, PATCH, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, x-access-token,access-control-allow-origin,access-control-allow-credentials,access-control-allow-headers';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        }
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    }
}

2 个答案:

答案 0 :(得分:0)

我相信您会忘记try_files行中的/index.html(请注意'/')。因此,在访问localhost / auth时,nginx尝试解析/usr/share/nginx/html/auth/index.html而不是/usr/share/nginx/html/index.html

尝试更换

try_files $uri $uri/ index.html;

通过

try_files $uri $uri/ /index.html;

答案 1 :(得分:0)

通过向AWS CDN云前端添加错误页面来解决此问题