【问题标题】:Cant access sub paths on Nginx + React router behind a proxy无法访问代理后面的 Nginx + React 路由器上的子路径
【发布时间】:2021-12-28 18:57:10
【问题描述】:

我有一个 nginx 服务器,本地 Web 应用程序在 4000 端口本地运行。我能够创建 Nginx 规则以通过代理加载它,但现在我只能通过主 url 访问该网站,例如“ https://app.domain.com”(这很好用),如果我尝试通过“https://app.domain.com/page”之类的任何链接输入,我会得到 404。

这是我当前的 nginx 配置;

server {
  # gzip
  gzip on;
  gzip_vary on;
  gzip_proxied any;
  gzip_comp_level 6;
  gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;

  # SSL configuration
  listen 443;
  listen [::]:443;
  expires $expires;
  ssl on;
  ssl_certificate /etc/ssl/app.crt;
  ssl_certificate_key /etc/ssl/app.key;

  index index.html;

  server_name app.domain.com;
  proxy_intercept_errors on;
  autoindex off;

  root /var/www/domain-app;

  # I am using this rule to allow files like icons or css to be accessed directly
  location ~ ^.+\..+$ {
    proxy_set_header Host $host;
    proxy_pass http://localhost:4000;
    proxy_redirect off;

    if (!-e $request_filename){
      rewrite https://$server_name break;
    }
    
    try_files $uri /index.html;
  }
  
  location / {
    proxy_set_header Host $host;
    proxy_pass http://localhost:4000;
    proxy_redirect off;

    try_files $uri /index.html;
  }
}

我在该位置尝试了类似的操作,它适用于根域和页面,但从“https://app.domain.com/page/sub”之类的子页面访问该站点失败;它加载了页面,但它试图在“https://app.domain.com/page/static/...”下找到资产

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

  set $fallback_file /index.html;
  if ($http_accept !~ text/html) {
      set $fallback_file /null;
  }
  try_files $uri $fallback_file;
}

【问题讨论】:

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


    【解决方案1】:

    好的,对于任何来这里的人,经过几个小时的研究,我找到了解决方案;

    问题毕竟不是我的 nginx 配置,而是 Create React App/react-router 的事情。

    为了使应用程序(而不是服务器)在所有子路径中正确替换资产的 URI,您的 package.json 中的主页需要与您的内部服务器/代理的 URL 匹配,例如我在“http://localhost:4000”本地托管代理,那么这也应该是 package.json 中的“主页”属性,与其他教程建议仅使用“./”不同,因为这不是一个单一的页面应用程序。

    Chhers!

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 1970-01-01
      • 2018-06-29
      • 2021-02-13
      • 2018-10-03
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多