# Nginx部署React项目至服务器二级目录实践
本文记录了一次
React项目使用Nginx部署至服务器二级目录的实践过程。
# 一、修改资源路径
React打包后的资源路径是/static/xxx.js这种形式,是从项目根路径(即nginx中的root设置的路径)开始的,如果要部署到二级目录,需要将其修改为./。
当然如果部署环境需要也可以改为../或其它。

如上图所示👆 ,在package.json中添加"homepage": ".",即可将资源的路径修改为./static/xxx.js这种形式。
# 二、在路由中添加basename
 
还是如上图所示👆 ,添加basename="/example",
此时,如果你的页面原来是localhost:8000/home,添加之后将会变为localhost:8000/example/home。
# 三、将项目打包之后部署
项目打包之后部署至Nginx中配置的root目录下的二级目录example。
# 1.简单配置
server {
  listen       8000;
  server_name  192.168.0.1;
  root   root_dir;
  location /{
    index index.html index.htm;
  }
  location ^~/example/ {
    index index.html index.htm;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
由于路由的存在,简单配置并不可行。
这种配置在路由跳转时会因为直接404。比如从/example/跳转到/example/home因为example目录下并无home目录而找不到资源。
# 2.对资源请求做特殊处理
server {
    listen       8000;
    server_name  192.168.0.1;
    root   root_dir;
    location /{
      index index.html index.htm;
      # autoindex on;
      # autoindex_exact_size off;
      # autoindex_localtime on;
    }
    location ^~/example/ {
      index index.html index.htm;
      try_files $uri $uri/ /example/index.html;
      location ~*  ^/([^/]+\.js)$ {
        alias /nginx-1.14.2/root_dir/example/js/$1;
      }
      location ~* ^/\.(js)$ {
        root root_dir/example/js/;
      }
      location ~*  ^/([^/]+\.css)$ {
        alias /nginx-1.14.2/root_dir/example/$1;
      }
      location ~* ^/\.(css)$ {
        root root_dir/example/;
      }
    }
  }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 要点
- try_files $uri $uri/ /example/index.html;:设置一个查找顺序。- 比如寻找 - xxx.js,寻找顺序为:- $uri=>- /root_dir/example/xxx.js;
- $uri/=>- /root_dir/example/xxx.js/index;
- /root_dir/example/index.html。
 
- location ~* ^/([^/]+\.js)$ { alias /nginx-1.14.2/root_dir/example/js/$1; } location ~* ^/\.(js)$ { root root_dir/example/js/; }1
 2
 3
 4
 5
 6
 7- 这一组是重定向资源路径,另一组也是一样的。它将 - .js的请求地址重定向到了- alias和- root指定的地址。- alias和- root的区别可以了解一下。
