Nginx同一个server部署多个静态资源目录 您所在的位置:网站首页 nginx访问其他服务器静态资源 Nginx同一个server部署多个静态资源目录

Nginx同一个server部署多个静态资源目录

2023-09-17 06:56| 来源: 网络整理| 查看: 265

一般情况,有时候业务需求,需要在一个server下面不同目录部署两个不同的项目。

比如 http://domain:port/admin 匹配的是 admin 项目

比如 http://domain:port/react 匹配的是 react 项目

我们在nginx.conf里面写一个新的server;

server { listen 6002; server_name **.**.**.**; gzip on; location /admin { alias /projects/admin/; #指定主页 index index.html; #自动跳转 autoindex on; } location /react { alias /projects/react/; #指定主页 index index.html; #自动跳转 autoindex on; } }

然后关闭 nginx

[root]# nginx -s stop

重启 nginx

[root]# nginx -c /etc/nginx/nginx.conf

总结:

这里需要注意的就是location中的路径匹配问题,root 和 alias 的区别;

# 错误写法,会报404 location /admin { root /projects/admin/; #指定主页 index index.html; #自动跳转 autoindex on; } location /react { root /projects/react/; #指定主页 index index.html; #自动跳转 autoindex on; } # 当你访问 http://***/admin # root ==> 实际指向的是 http://***/admin/projects/admin/, 这个时候肯定找不到index.html # alias ==> 实际指向的是 http://***/admin, 可以在/projects/admin/找到index.html

document:

In case of the root directive, full path is appended to the root including the location part, where as in case of the alias directive, only the portion of the path NOT including the location part is appended to the alias.

Let’s say we have the config

location /static/ { root /var/www/app/static/; autoindex off; }

In this case the final path that Nginx will derive will be

/var/www/app/static/static

This is going to return 404 since there is no static/ within static/

This is because the location part is appended to the path specified in the root. Hence, with root, the correct way is

location /static/ { root /var/www/app/; autoindex off; }

On the other hand, with alias, the location part gets dropped. So for the config

location /static/ { alias /var/www/app/static/; autoindex off; }

the final path will correctly be formed as

/var/www/app/static

来源:https://blog.csdn.net/qq_26003101/article/details/100799451

 

=================第二篇:解释root和alias的区别=================

公司测试环境使用nginx部署多个前端项目。网上查到了两个办法:

在配置文件中增加多个location,每个location对应一个项目 比如使用80端口,location / 访问官网; location /train 访问培训管理系统配置多个站点 我选择了配置多个location。 location / { root /data/html/; index index.html index.html; } location /train { root /data/trainning/; index index.html index.html; } 12345678

配置完以后访问。http://xxxx/train 提示404 找了好久才搞明白, location如果一个特定的url 要使用别名,不能用root,alias指定的目录是准确的,root是指定目录的上级目录,改动后即可以使用了

location /train { alias /data/trainning/; index index.html index.html; }

补充: 留言中有小伙伴问及alias和root区别,个人理解: root与alias主要区别在于nginx如何解释location后面的uri,这会使两者分别以不同的方式将请求映射到服务器文件上。 root的处理结果是:root路径+location路径 alias的处理结果是:使用alias路径替换location路径 alias是一个目录别名的定义,root则是最上层目录的定义。 还有一个重要的区别是alias后面必须要用“/”结束,否则会找不到文件的。。。而root则可有可无~~

 来源:https://blog.csdn.net/lizhiyuan_eagle/article/details/90639448



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有