Heim  >  Artikel  >  Backend-Entwicklung  >  nginx-几个关于location pattern的问题

nginx-几个关于location pattern的问题

WBOY
WBOYOriginal
2016-08-29 08:50:551218Durchsuche

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

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

<code>location /doc {
    alias /home/user/doc;
}
</code>

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

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

<code>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;
    }
}
</code>

在主服务器这样配置:

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

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

<code>location /doc/ {
            proxy_pass http://localhost:8000/;
        }
</code>

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

回复内容:

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

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

<code>location /doc {
    alias /home/user/doc;
}
</code>

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

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

<code>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;
    }
}
</code>

在主服务器这样配置:

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

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

<code>location /doc/ {
            proxy_pass http://localhost:8000/;
        }
</code>

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn