Nginx try_files不适用于我的Vue应用

时间:2019-05-28 19:35:48

标签: docker nginx vue.js

我目前有一个使用Nginx来服务我的Vue应用程序的Docker容器。我正在使用的配置如下:

worker_processes 5;  ## Default: 1
error_log /usr/share/nginx/nginx_logs/error.log;
pid /usr/share/nginx/nginx_logs/nginx.pid;
worker_rlimit_nofile 8192;

events {
  worker_connections  4096;  ## Default: 1024
}

http {
  include /usr/share/nginx/conf/mime.types;
  include /usr/share/nginx/proxy.conf;
  index index.html index.htm;

  default_type application/octet-stream;
  log_format main '$remote_addr - $remote_user [$time_local]  $status '
    '"$request" $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';
  access_log /usr/share/nginx/nginx_logs/access.log main;
  sendfile on;
  tcp_nopush on;
  server_names_hash_bucket_size 128;

  server {
    listen 80;
    server_name spshub.org www.spshub.org;
    root /usr/share/nginx/html;
    access_log /usr/share/nginx/nginx_logs/spshub.access.log main;

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

我认为通过包含try_files,它将在刷新时重定向回index.html,但是我得到的只是404错误消息。我使用的Vue路由器的历史记录模式已打开,并且我的基本URL设置为“ /”。当它打到“ /”时,它将重定向到“ / home”。导航正常,但是刷新是在出错时进行的。如果查看日志,它将尝试在根目录中查找“ home”。有办法解决这个问题吗?

这是从日志中获取的:

2019/05/28 19:39:07 [error] 6#6: *15 open() "/usr/share/nginx/html/home" failed (2: No such file or directory), client: <client-ip>, server: localhost, request: "GET /home HTTP/1.1", host: "<public-host-ip>"
<client-ip> - - [28/May/2019:19:39:07 +0000] "GET /home HTTP/1.1" 404 555 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" "-"
2019/05/28 19:39:08 [error] 6#6: *15 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: <client-ip>, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "<public-host-ip>", referrer: "http://<public-host-ip>/home"
<client-ip> - - [28/May/2019:19:39:08 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://<public-host-ip>/home" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" "-"

我的Dockerfile如下:

FROM node:lts-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build:prod

# Production deployment
FROM nginx:stable-alpine as production
COPY --from=build /app/dist /usr/share/nginx/html
COPY /nginx /usr/share/nginx
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

复制到nginx / html文件夹中的dist文件夹如下所示:

dist\main.243ea19f.js.map
dist\main.243ea19f.js
dist\main.2bb2bbfa.css.map
dist\main.2bb2bbfa.css
dist\index.html
dist\assets\images\

1 个答案:

答案 0 :(得分:0)

从外观上看,如注释中所述。您需要更改

COPY /nginx /usr/share/nginx

TO

COPY /nginx /etc/nginx/

这假设您的/nginx目录中有一个nginx.config文件。