nginx-几个关于location pattern的问题

原创
2016-08-29 08:50:55673浏览

查了好多资料都没有搞懂的几个问题。

第一个问题,如果我的location配置是这样的:

location /doc {
    alias /home/user/doc;
}

那我访问http://localhost/doc/a.html的时候实际上nginx是读取了/home/usr/doc/a.html,如果我访问的是http://localhost/docs/a.html甚至是http://localhost/docsioajsfopajowejfasd那nginx实际上会尝试读取哪个文件?

第二个问题,如果我将doc配置成一个服务器,再反向代理。

server {
    listen 8000;
    server_name doc;
    root /home/user/doc;
    
    index index.html index.htm index.nginx-debian.html;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }
}

在主服务器这样配置:

server {
    listen 80;
    ....
    location /doc {
        proxy_pass http://localhost:8000/;
    }
    }

这样配置时访问http://localhost/doc/,如果index文件引用了静态文件,静态文件会变成404,浏览器会尝试获取http://localhost/js/xxx.js而不是http://localhost/doc/js/xxx.js,如果在pattern后面加上/变成

location /doc/ {
            proxy_pass http://localhost:8000/;
        }

就没有问题,但如果是第一个问题中的location配置,浏览器会正确寻找http://localhost/doc/js/xxx.js。这搞得我很困惑,结尾加不加/究竟有什么影响?为什么alias和proxy_pass会出现不同的结果?

回复内容:

查了好多资料都没有搞懂的几个问题。

第一个问题,如果我的location配置是这样的:

location /doc {
    alias /home/user/doc;
}

那我访问http://localhost/doc/a.html的时候实际上nginx是读取了/home/usr/doc/a.html,如果我访问的是http://localhost/docs/a.html甚至是http://localhost/docsioajsfopajowejfasd那nginx实际上会尝试读取哪个文件?

第二个问题,如果我将doc配置成一个服务器,再反向代理。

server {
    listen 8000;
    server_name doc;
    root /home/user/doc;
    
    index index.html index.htm index.nginx-debian.html;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }
}

在主服务器这样配置:

server {
    listen 80;
    ....
    location /doc {
        proxy_pass http://localhost:8000/;
    }
    }

这样配置时访问http://localhost/doc/,如果index文件引用了静态文件,静态文件会变成404,浏览器会尝试获取http://localhost/js/xxx.js而不是http://localhost/doc/js/xxx.js,如果在pattern后面加上/变成

location /doc/ {
            proxy_pass http://localhost:8000/;
        }

就没有问题,但如果是第一个问题中的location配置,浏览器会正确寻找http://localhost/doc/js/xxx.js。这搞得我很困惑,结尾加不加/究竟有什么影响?为什么alias和proxy_pass会出现不同的结果?

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。