如何配置 NGINX 来重新路由基于子域构建的 React Router 应用程序?

Ait*_*ura 2 nginx reactjs react-router

我目前正在使用 React 和 React 路由器构建一个应用程序,该应用程序在由 nginx 和 docker 提供服务时工作得很好,但是一旦我重新加载或复制/粘贴 url,nginx 就会给出 404 错误,因为配置无法到达指定的位置由我来呈现错误页面,没有它就是 500。另外,我的整个应用程序都在子域下运行,这使得我看到并尝试过的一些答案不起作用,因为我似乎错过了正确告诉 nginx 在相应目录中哪里可以找到我的 index.html 的东西。

现在我的配置文件如下所示:

nginx.conf

    user www-data;
    worker_processes 4;
    pid /run/nginx.pid;
    
    events {
            worker_connections 768;
            # multi_accept on;
    }
    
    http {
    
            ##
            # Basic Settings
            ##
    
            sendfile on;
            tcp_nopush on;
            tcp_nodelay on;
            keepalive_timeout 65;
            types_hash_max_size 2048;
    
            # server_names_hash_bucket_size 64;
            # server_name_in_redirect off;
    
            include /etc/nginx/mime.types;
            default_type application/octet-stream;
    
            ##
            # SSL Settings
            ##
    
            ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
            ssl_prefer_server_ciphers on;
    
            ##
            # Logging Settings
            ##
    
            access_log /var/log/nginx/access.log;
            error_log /var/log/nginx/error.log;
    
            ##
            # Gzip Settings
            ##
    
            gzip on;
            gzip_disable "msie6";

            ##
            # Virtual Host Configs
            ##

            include /etc/nginx/conf.d/*.conf;
            include /etc/nginx/sites-enabled/*;
    }
Run Code Online (Sandbox Code Playgroud)

默认启用内部站点

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;
        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ index.html  =404;
        }

        location = /example1/example2/ {
                try_files $uri $uri/ index.html =404;
        }

}
Run Code Online (Sandbox Code Playgroud)

我还在反应路由器中使用 browserHistory

pot*_*non 7

我为此奋斗了太久。由于某种原因,我无法掌握其他类似问题的任何已接受答案。在谷歌上搜索这个问题时需要经历很多事情,并且许多解决方案都建议对 uri 进行相当复杂的重定向和解析。当我做对时,我自己想出的解决方案是很明显的。

我使用 create-react-app 创建了一个 React 应用程序。在开发时使用开发服务器进行测试,直接子链接,一切正常。我想将其部署在子域 /ui/ 下的 nginx 容器中。

如果没有潜艇,一切都会按预期工作,但添加基地浴不知何故把事情搞砸了。

跑了一圈之后,这就是最终的解决方案。关键点:

  1. 将基本名称设置为您的 BrowserRouter
  2. 将主页设置为 package.json
  3. 以子文件夹 uri 指向正确文件夹的方式提供静态文件

App.js 或任何您可能用作顶级组件的内容:

<BrowserRouter basename="/ui">
    <Switch>
        <Route path="/results" component={Results} />
        <Route path="/testing" component={Testing} />
    </Switch>
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)

然后package.json:

...
"homepage": "/ui"
...
Run Code Online (Sandbox Code Playgroud)

我的整个 nginx 设置:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    server {
      listen       80;  

      location /ui/ {
        root   /app;
        try_files $uri $uri/ /ui/index.html =404;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dockerfile:

FROM node:alpine as build-step
WORKDIR /app
COPY project/package.json /app
RUN npm install
COPY project/ /app
RUN npm run build

FROM nginx
COPY --from=build-step /app/build /app/ui
COPY nginx/nginx.conf /etc/nginx/nginx.conf
Run Code Online (Sandbox Code Playgroud)

.dockerignore

project/node_modules
project/build
Run Code Online (Sandbox Code Playgroud)

我的构建脚本(./start-site.sh)

set -e
docker build -t mysite .
docker run --rm --name ui -p 80:80 mysite
Run Code Online (Sandbox Code Playgroud)

为什么这有效?

当请求例如js块时,浏览器完成的请求是:

http://localhost/ui/static/js/main.c1ffd94a.chunk.js

Nginx 使用

/ui/static/js/main.c1ffd94a.chunk.js

作为 uri,并尝试从您定义的根中查找匹配的文件,无论是否附加斜杠。确实有一个匹配的文件要返回,并且它有效。

您的反应应用程序路由页面的请求如下:

http://localhost/ui/results/8997/

显然没有找到匹配的文件,所以nginx返回

/ui/index.html

这是你的应用程序的入口点,react-router 解析 url。这还会捕获 /ui 下的任何 404,由您的 React 应用程序处理。

你可能已经明白了这一点,但至少下一个拼命谷歌搜索这个问题的人会有一些东西可以读。