【问题标题】:nginx tries to find index.html in a directory according to the uringinx尝试根据uri在某个目录中查找index.html
【发布时间】:2018-07-16 17:26:06
【问题描述】:

我有一个简单的 nginx 配置来服务我的 React 应用程序:

server {
    listen 80;
    root /usr/share/nginx/html;

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

我有路线/login。当我通过 React-Router 从 localhost/ 转到 localhost/login 时,一切正常。但是当我在浏览器中输入localhost/login 时,我得到了 404 错误。

确切地说,对于localhost/login,我在 nginx 控制台中得到"/usr/share/nginx/html/login" failed (2: No such file or directory)。 对于localhost/login/,我得到"/usr/share/nginx/html/login/index.html" is not found (2: No such file or directory)

我不明白为什么 nginx 一直在 /usr/share/nginx/html/login/ 中寻找 index.html 而不是 /usr/share/nginx/html/。任何想法我做错了什么?

【问题讨论】:

  • 通过路径/usr/share/nginx/html有一个index.html?
  • 是的,那个目录里有index.html
  • 你想通过路由/login打开你的应用index.html吗?
  • 是的,没错,index,html 在任何路线上
  • 我已经更新了我的答案尝试改变你的规则 try_files 就像我的答案一样

标签: reactjs nginx react-router


【解决方案1】:

好吧,我的错,看起来我只是搞砸了配置文件。 在我的 Dockerfile 中,我做了以下操作

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

虽然很明显,nginx 不会在 conf.default 文件中查找配置。

所以我创建了nginx.conf 文件:

events {
    worker_connections  1024;
}

http {
    server {
        listen 80;
        root /usr/share/nginx/html;

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

并写在Dockerfile

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

这解决了问题。感谢您的帮助!

【讨论】:

    【解决方案2】:

    你不需要location

    尝试像那里一样更改配置中的代码

    server {
        listen 80;
        root /usr/share/nginx/html;
        index index.html;
        location / {
          try_files /index.html =404;
      }
    }
    

    如果你有另一个静态文件也添加这个代码,(在location / {}块之后)

    location /files/ { 
      autoindex on;
      root /var/www/[your repo name]/files;
    }
    

    【讨论】:

    • 还是一样的行为
    猜你喜欢
    • 2014-07-20
    • 2016-06-24
    • 2019-10-31
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2013-07-06
    • 2019-05-12
    相关资源
    最近更新 更多