“携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天,点击查看活动详情”
在工作中,有些时候,部署静态资源时,不是在域名下的根目录,而是在子目录下。
create-react-app解决方法
create-react-app针对此有一个解决方法,可以查看这里 create-react-app中是使用package的homepage来指定域名路径,但是不能根据环境来决定是否需要子路径。
Nginx配置
这个时候可以使用如下方式进行nginx配置。
location /test {
root /software/www/web;
index index.html;
try_files $uri $uri/ /test/index.html;
}
location / {
root /software/www/web/build;
index index.html;
try_files $uri $uri/ /index.html;
}
其中/test为子路径。访问domain.com/test。
root和alias
这两个都可以用来指定访问的nginx的主目录,其中root可以在service和location中设置,alias只能在location中设置,用来表示路径的别名。 两个的主要区别是解析url路径的方式不同。
root
设置root后,最终解析的路径为root+location中指定的url,比如
# 设置url访问路径为子路径
location /test {
root /software/www/web;
index index.html;
try_files $uri $uri/ /test/index.html;
}
最终会解析到/software/www/web/test文件夹下的资源文件。访问domain.com/test
# 设置访问路径为根路径,在域名指定的根目录下
location / {
root /software/www/web/build;
index index.html;
try_files $uri $uri/ /index.html;
}
此时会解析到/software/www/web/build文件夹下,访问domain.com/即可
alias
设置alias后,会使用alias的路径替换location url,但是在设置alias时,路径要用/结尾。
location /test {
alias /software/www/web/test/;
index index.html;
try_files $uri $uri/ /test/index.html;
}
try_files
通过配合location,起到部分替换rewrite的配置方式,提高解析效率。现在一般是前端为SPA页面时,重新指定一下查找路径。由于SPA页面只有一个html入口文件,所以在路由改变时,需要重新指定一下查找路径,否则会找不到,报404错误。 此处在设置子目录后,需要在最后查找顺序里,指定下子目录文件夹,否则也会找不到html文件。
create-react-app自定义配置
在配置了nginx后,就可以在react中配置PUBLIC_URL来指定访问域名下的子目录。 为了解决不同环境下,设置不同的子目录的需求,可以在.env.xxx文件中设置
PUBLIC_URL=/test/
如果本地有使用react-router的话,还需要指定下basename,
const root = process.env.PUBLIC_URL
<BrowserRouter basename={root}>
<App />
</BrowserRouter>
以上就是在create-react-app中不使用homepage指定访问域名子目录的方法。