我目前正在使用 Nginx 作为反向代理并为我的静态 Assets 提供服务。我使用的是 React Router 的 HashLocation 设置,因为它是默认设置,它允许我毫无问题地刷新路由,不需要任何额外的配置,但使用该设置的问题是 url 必须有/#/前缀我的路线(例如 http://example-app.com/#/signup )。

我现在尝试切换到 React Router 的 HistoryLocation 设置,但我不知道如何正确配置 Nginx 为所有路由提供 index.html(例如 http://example-app.com/signup )。

这是我的初始 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 Cannot GET 错误。

if (!-e $request_filename){ 
  rewrite ^(.*)$ /index.html break; 
}  

location/ block 中。这允许我刷新并直接访问顶级位置的路由,但现在我无法提交 PUT/POST 请求,而是返回不允许的 405 方法。我可以看到请求没有得到正确处理,因为我现在添加的配置将我的所有请求重写到/index.html,而这就是我的 API 接收所有请求的地方,但我不知道如何完成这两个任务将我的 PUT/POST 请求提交到正确的资源,并且能够刷新和访问我的路线。

请您参考如下方法:

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

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

我知道您的示例使用 @proxy 更为复杂,但上述内容对于我的应用程序来说效果很好。


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!