【问题标题】:How to configure NGINX to reroute a React Router app built on sub domains?如何配置 NGINX 以重新路由基于子域的 React Router 应用程序?
【发布时间】:2021-04-01 05:32:43
【问题描述】:

我目前正在使用 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/*;
    }

默认在网站内启用

##
# 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;
        }

}

我也在使用 browserHistory 和我的 react 路由器

【问题讨论】:

    标签: reactjs nginx react-router


    【解决方案1】:

    我与这个斗争太久了。出于某种原因,我无法掌握其他类似问题的任何公认答案。在谷歌上搜索这个问题时有很多事情要做,许多解决方案都建议对 uri 进行相当复杂的重定向和解析。当我做对时,我自己想出的解决方案很明显。

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

    如果没有 sub,一切都按预期工作,但是添加那个 basebath 不知何故把事情搞砸了。

    跑完圈,这是最终的解决方案。要点:

    1. 为您的 BrowserRouter 设置 basename
    2. 将主页设置为 package.json
    3. 以这样的方式提供静态文件,使子文件夹 uri 指向正确的文件夹

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

    <BrowserRouter basename="/ui">
        <Switch>
            <Route path="/results" component={Results} />
            <Route path="/testing" component={Testing} />
        </Switch>
    </BrowserRouter>
    

    然后是package.json:

    ...
    "homepage": "/ui"
    ...
    

    我的整个 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;
            }
        }
    }
    

    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
    

    .dockerignore

    project/node_modules
    project/build
    

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

    set -e
    docker build -t mysite .
    docker run --rm --name ui -p 80:80 mysite
    

    为什么会这样?

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

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

    Nginx 使用

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

    作为 uri,并尝试从您定义的根目录中查找匹配的文件,无论是否附加斜线。确实有一个匹配的文件要返回,并且可以正常工作。

    请求您的 react 应用路由页面如下:

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

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

    /ui/index.html

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

    你可能已经想通了,但至少下一个拼命搜索这个的人会有一些东西可以阅读。

    【讨论】:

      猜你喜欢
      • 2011-11-22
      • 2020-09-05
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 2018-06-09
      • 2020-02-29
      • 2021-02-07
      • 1970-01-01
      相关资源
      最近更新 更多