无法使用 url 通过 nginx 在 React 中导航

Abd*_*had 5 nginx reactjs nginx-location nginx-config

我正在使用 nginx(反应前端)提供静态文件。我为每个页面使用了不同的网址,例如 /login /user /home 。

我的 nginx 不会将这些重定向到我的 index.html 文件。

我做了一些更改,现在我也无法访问我的主页。它返回无法获取/。

这是我的 nginx.conf 文件。我在 Windows 上运行它。我的index.html 位于build 文件夹内。如何让我的nginx使用reactjs中的Router和Link,以便我可以通过引用链接或通过导航栏获取页面?

worker_processes  5;

events {
    worker_connections  1024;
}


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

    sendfile        on;
    keepalive_timeout  65;


    server {
        listen   80;
        server_name  ip;

        location / {
            root   /Users/username/projectfolder/build;    
            index  index.html index.htm;
            try_files $uri $uri/ index.html;
            proxy_pass http://ipaddress:portnumber;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
         }
     }
 }
Run Code Online (Sandbox Code Playgroud)

更新:

我尝试过以下配置

server {
        listen some_port;
        server_name some_ip;
        root C:\\nginx-1.17.1\\build\\;
        index  index.html index.htm;
        location /test/ {   
            alias C:\\nginx-1.17.1\\build\\;
            index  index.html index.htm;
            try_files $uri \\index.html;
            #internal;

            #return index;
        }
        location = /index.html {
        # no try_files here
        return 502;
    }
        location / {  
            #root   C:\\Users\\DEV-a0a02yc\\insurance_automation\\build;
            try_files $uri $uri\ \index.html?$args;
            #try_files $uri/ index.html;
            proxy_pass http://some_ip:some_port;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }
Run Code Online (Sandbox Code Playgroud)

在 /test/ url 中,我收到一个空白页面和一个重写/内部重定向错误,内容如下:

2019/07/01 09:53:22 [error] 17820#18008: *1 rewrite or internal redirection cycle while internally redirecting to "/favicon.ico\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html"
Run Code Online (Sandbox Code Playgroud)

这是我的网络选项卡: 在此输入图像描述

输入此网址时,如何在此处提供我的 index.html 文件以处理重定向?

sea*_*pip 5

您的配置中的代理线路有哪些用途?

您不应该从 html 文件提供服务或代理传递到不同的地址吗?

我建议尝试从配置中删除代理线路。

另外,在不相关的注释中,proxy_pass 行无效。服务器地址“ipaddress”是一个很长的地址(尽管对于 dns 来说并非不可能),并且端口“portnumber”肯定是无效的。

因此,所需的最低配置如下:

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

root定义您的 React 构建文件夹位置,并try_files定义 nginx 应查看请求的文件是否存在,如果不存在,则提供index.html.