【问题标题】:react, nginx reverse proxy and docker giving 404反应,nginx反向代理和docker给404
【发布时间】:2020-11-28 02:37:11
【问题描述】:

所以我的网站有两个部分:

1- /api、/oauth 和 /assets 位置被重定向到 laravel 应用程序并使用简单的 proxy_pass 到它们的 docker 端口

2- web 应用程序,它是一个反应应用程序。我们制作 Web 应用程序的映像(因此没有文件传输到服务器)并在端口上运行它,比如 3000。

这是我的 Nginx 配置总结:

server {
        server_name mywebsite.com;

        location /api {
                proxy_pass http://localhost:8080/api;
                proxy_set_header Host $host;
        } //the same with other Laravel paths

        location / {
                proxy_pass http://localhost:3000/;
                proxy_set_header Host $host;
                proxy_redirect off;
        }
}

问题是如果用户转到一个页面,比如 site.com/profile 并刷新它,他们会收到 404 错误。谷歌搜索很多导致使用 try_files .. index.html 处理本地文件,但在使用 proxy_pass 和 docker 图像时不可用。

更多的谷歌搜索让我找到了一个真正有效的解决方案:

server {
        server_name mywebsite.com;

        location /api {
                proxy_pass http://localhost:8080/api;
                proxy_set_header Host $host;
        } //the same with other Laravel paths

        location / {
                proxy_pass http://localhost:3000/;
                proxy_set_header Host $host;
                proxy_redirect off;
                proxy_intercept_errors on;
                recursive_error_pages on;
                error_page 404 = @rewrite_proxy;
        }

        location @rewrite_proxy {
                rewrite ^/(.*)$ /index.html?$1 break;
                proxy_pass http://localhost:3000;
                proxy_set_header Host $host;
        }
}

它非常棒,就像一个魅力。现在的问题是,我正在寻找一种解决方案来控制网络应用程序的实际 404 错误,因此它可以根据 URL 以不同的方式做出反应。有什么建议吗?

【问题讨论】:

    标签: reactjs docker nginx react-router reverse-proxy


    【解决方案1】:

    看看这个,希望对你有帮助

     server {
    listen 80;
    
    location /api {
      proxy_pass         http://backend/api;
      proxy_redirect     off;
      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-Host $server_name;
    }
    
    location / {
      proxy_pass         http://frontend;
      proxy_redirect     off;
      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-Host $server_name;
      try_files $uri     $uri/ /index.html @backend;
       error_page        405 @backend;
    }
    location @backend {
        proxy_pass http://frontend;
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_set_header   X-Real-IP         $remote_addr;
    }
    

    }

    【讨论】:

    • 你应该解释为什么这会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-07-22
    • 2021-11-13
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2018-05-31
    相关资源
    最近更新 更多