Post 如何使用React Router HistoryLocation配置Nginx?

Post 如何使用React Router HistoryLocation配置Nginx?,post,nginx,reactjs,react-router,html5-history,Post,Nginx,Reactjs,React Router,Html5 History,我目前使用Nginx作为反向代理,并为我的静态资产提供服务。我使用React Router的HashLocation设置,因为这是默认设置,它允许我在路由上刷新,没有问题,也不需要任何其他配置,但使用该设置的问题是url必须有/#/prepending我的路由(例如) 我现在正试图切换到React路由器的HistoryLocation设置,但我不知道如何正确配置Nginx为所有路由(例如)提供index.html服务 以下是我的初始nginx设置(不包括我的mime.types文件): ngin

我目前使用Nginx作为反向代理,并为我的静态资产提供服务。我使用React Router的HashLocation设置,因为这是默认设置,它允许我在路由上刷新,没有问题,也不需要任何其他配置,但使用该设置的问题是url必须有/#/prepending我的路由(例如)

我现在正试图切换到React路由器的HistoryLocation设置,但我不知道如何正确配置Nginx为所有路由(例如)提供index.html服务

以下是我的初始nginx设置(不包括我的mime.types文件):

nginx.conf

# The maximum number of connections for Nginx is calculated by:
# max_clients = worker_processes * worker_connections
worker_processes auto;

# Process needs to run in foreground within container    
daemon off;

events {
  worker_connections 1024;
}

http {
  # Hide nginx version information.
  server_tokens off;

  # Define the MIME types for files.
  include       /etc/nginx/mime.types;

  # Update charset_types due to updated mime.types
  charset_types
    text/xml
    text/plain 
    text/vnd.wap.wml
    application/x-javascript
    application/rss+xml
    text/css
    application/javascript
    application/json;

  # Speed up file transfers by using sendfile() to copy directly
  # between descriptors rather than using read()/write().
  sendfile      on;

  # Define upstream servers
  upstream node-app {
    ip_hash;
    server 192.168.59.103:8000;
  }

  include sites-enabled/*;
}
默认值

server {
  listen  80;
  root    /var/www/dist;
  index   index.html index.htm;

  location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires 1d;
  }

  location @proxy {
    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-NginX-Proxy true;

    proxy_http_version  1.1;
    proxy_redirect      off;
    proxy_pass          http://node-app;
    proxy_cache_bypass  $http_upgrade;
  }

  location / {
    try_files $uri $uri/ @proxy;
  }

}
当我使用HashLocation时,这个设置工作得很好,但是在更改为HistoryLocation(我所做的唯一更改)之后,当尝试刷新子路由的url时,我得到一个404无法得到的结果

if (!-e $request_filename){
  rewrite ^(.*)$ /index.html break;
} 
位置/
块中。这允许我刷新并直接访问作为顶级位置的路由,但现在我不能提交PUT/POST请求,而是返回一个不允许的405方法。我可以看到请求没有得到正确处理,因为我添加的配置现在将我的所有请求重写为/index.html,这就是我的API接收所有请求的地方,但我不知道如何实现将PUT/POST请求提交到正确的资源,以及刷新和访问我的路由

location / {
    try_files $uri /your/index.html;
}


我知道您的示例对于
@proxy
更为复杂,但是上面的操作对于我的应用程序来说很好。

我也遇到了这个问题,您找到解决方案了吗?我也在努力解决这个问题。我尝试更改应用程序的路径,并尝试从该目录相对地运行路由器应用程序。