刷新时找不到Nginx 404,同样用try_files $uri $uri //index.html =404;

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

我不知道如何解决刷新时的 404 错误。 这是我的配置的相关部分:


server {
    server_name    example.com;
     location / {
        proxy_pass http://192.168.x.y:5000; # Proxy requests to Node web server on port 8000
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    location /api {
        proxy_pass http://192.168.x.y:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
}
server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot
    server_name    example.com;
    listen 80;
    return 404; # managed by Certbot
}

我也尝试过在“location /”部分使用try_files,但没有成功,或者可能是我做错了。

try_files $uri $uri/ /index.html =404;

我的index.html 在以下路径的网络服务器中提供服务:

/home/ubuntu/web_server/public/index.html

通过这样的 docker 容器安装

   volumes:
      - ./nginx_data:/etc/nginx/conf.d       # Nginx configurations
      - /etc/letsencrypt/:/etc/letsencrypt/  # Certificates for https
http-status-code-404 refresh nginx-reverse-proxy nginx-config nginx-location
1个回答
0
投票

这是更新后的 nginx 配置

server {
    server_name example.com;

    location / {
        # Serve the index.html file for all unmatched routes
        try_files $uri $uri/ /index.html;

        # Proxy pass to the backend server
        proxy_pass http://192.168.x.y:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /api {
        proxy_pass http://192.168.x.y:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
}

server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    server_name example.com;
    listen 80;
    return 404; # managed by Certbot
}

这将使您的 SPA 始终加载并让客户端路由器处理导航。

sudo systemctl restart nginx

以上命令重启nginx

© www.soinside.com 2019 - 2024. All rights reserved.