nginx尝试根据uri在目录中查找index.html

pha*_*ton 5 nginx reactjs react-router

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

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

    location / {
        try_files $uri $uri/ /index.html;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

确切地说,因为localhost/login我进入"/usr/share/nginx/html/login" failed (2: No such file or directory)了 nginx 控制台。因为localhost/login/我得到"/usr/share/nginx/html/login/index.html" is not found (2: No such file or directory)

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

Igo*_*ova 2

你不需要location

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

server {
    listen 80;
    root /usr/share/nginx/html;
    index index.html;
    location / {
      try_files /index.html =404;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

location /files/ { 
  autoindex on;
  root /var/www/[your repo name]/files;
}
Run Code Online (Sandbox Code Playgroud)