首页 > 解决方案 > 无法使用 url 导航通过 nginx 做出反应

问题描述

我正在使用 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;
         }
     }
 }

更新:

我尝试了以下配置

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;
        }
    }

在 /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"

这是我的网络标签: 在此处输入图像描述

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

标签: reactjsnginxnginx-locationnginx-config

解决方案


您的配置中的代理行是什么?

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

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

同样在不相关的注释中,proxy_pass 行无效。服务器地址“ipaddress”是一个很长的延伸(虽然不是不可能的 dns),端口“portnumber”肯定是无效的。

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

location / {
    root /folder/subfolder/build;
    try_files $uri /index.html;
}

root定义你的 react 构建文件夹位置,并try_files定义 nginx 应该查看请求的文件是否存在,如果不存在,它服务于index.html.


推荐阅读