nginx的root与alias

最近在做一个新的项目,以下都称呼为new项目吧。

new项目上测试环境时,要求使用二级域名,https://yuming.cn/new。开始的方案是要把文件都打包到build/new/目录下。这样的话发布到服务器上,访问二级域名https://yuming.cn/new 即可访问到/data/site/new-fe-test/new/index.html文件。nginx的配置如下

server {

    listen  80;

    server_name yuming.cn;

    root /data/site/yuming-fe-test;

    index index.php index.html index.htm;

    location / {

        root /data/site/yuming-fe-test;

        try_files $uri $uri/ /index.html;

    }

    location /new {

        root /data/site/new-fe-test;

        try_files $uri /new/index.html;

    }

    error_log  /var/log/nginx/yuming-fe_error.log;

    access_log /var/log/nginx/yuming-fe_access.log;

}

后来组长提出,放在new/目录的工作下不应该前端项目中操作。然后他对nginx进行了改造,前端项目正常打包到build/目录即可,

nginx修改为如下。

location /new {

    alias /data/site/new-fe-test/;

    try_files $uri $uri/  index.html;

}

延展学习

nginx小白的我进行了一下学习总结,关键词:alias,root,$uri

alias、root是nginx指定文件路径的两种方式,

使用方法和作用域

root

语法: root path

默认值:root html

配置段:http、server、location、if

alias

语法:alias paht

配置段:location

区别

root与alias区别主要在于nginx是如何解释location后边的uri,这会是两者分别以不同方式将请求映射到服务器的文件上。(alias是一个目录别名的定义,root则是最上层目录的定义)。

root的处理结果是:root路径+location路径

alias的处理结果是:使用alias路径替换location路径

实例

location /t/ {

    root /www/root/html/

}

如果请求一个uri是/t/a.html时,web服务器会将服务器上的/www/root/html/t/a.html返回

location /t/ {

    alias /www/root/html/

}

如果请求一个uri是/t/a.html时,web服务器会将服务器上的/www/root/html/a.html返回,因为alias会吧location后边的配置路径/t/丢弃掉。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容