php - nginx-几个关于location pattern的问题

 米米丫头2502860283 发布于 2022-11-14 11:16

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

第一个问题,如果我的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会出现不同的结果?

1 个回答
  • 不是root和proxy_pass的区别,而是proxy_pass有一个特殊逻辑,如果proxy_pass后面有路径就会触发它,注意一个“/”也是路径,如下图。
    proxy_pass http://127.0.0.1/;
    proxy_pass http://127.0.0.1;

    官方资料:
    http://nginx.org/en/docs/http...

    Syntax: proxy_pass URL;
    Sets the protocol and address of a proxied server and an optional URI(修改成PATH更加准确,和便于理解) to which a location should be mapped.

    If the proxy_pass directive is specified with a URI(路径,下同), then when a
    request is passed to the server, the part of a normalized request URI
    matching the location is replaced by a URI specified in the directive:
    location /name/ {

    proxy_pass http://127.0.0.1/remote/; }
    

    If proxy_pass is specified without a URI(路径,下同), the request URI is passed to
    the server in the same form as sent by a client when the original
    request is processed, or the full normalized request URI is passed
    when processing the changed URI: location /some/path/ {

    proxy_pass http://127.0.0.1; }
    2022-11-14 12:47 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有