在浏览器中刷新页面时在 nginx 中获取 404

问题描述 投票:0回答:1

在 Vultr 中部署了我的 React 应用程序,下面是我的

nginx
配置。导航到页面并在刷新浏览器时抛出 404 错误。我在位置下添加了
try_files $uri /index.html;
,并通过运行以下命令重新启动了nginx。有人可以建议解决这个问题吗!

$ sudo systemctl restart nginx

但是在添加

try_files $uri /index.html; 
时出现错误系统错误:net::ERR_BLOCKED_BY_CLIENT groupByTags.js:38 类型错误:无法读取未定义的属性(读取“0”) 在 groupByTags.js:35:39 在 c (regeneratorRuntime.js:44:17)

// nginx 配置

server {
        
                listen 80;
                server_name example.com www.example.com;
                root /var/www/example.com/build;
                index index.html;
        
            location /service {
               proxy_pass http://localhost:8000;
               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;
               try_files $uri /index.html;    ## try_files $uri $uri/ /index.html; ## tried this one
            }
    
    }
reactjs nginx nginx-config
1个回答
0
投票

我能够弄清楚这一点。我在 nginx conf 文件中添加了另一个

location / { try_files $uri /index.html; }
块解决了页面刷新问题。
location /service {...
的第二个块用于访问现有的 api 服务。

在我的例子中,我的 api 服务端点如下所示,例如:

service/listOfBlogs
。所以如果你的api端点以
api/some_end_point
开头,那么位置块应该写成
location /api {...

下面列出了完整的 nginx conf:

server {
        
            listen 80;
            server_name example.com www.example.com;
            root /var/www/example.com/build;
            index index.html;
            
            location / {
                try_files $uri /index.html;
            }

        
            location /service {
               proxy_pass http://localhost:8000;
               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;
            }
        
    }
© www.soinside.com 2019 - 2024. All rights reserved.