php - nginx-几个关于location pattern的问题
怪我咯
怪我咯 2017-04-11 10:08:23
[PHP讨论组]

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

第一个问题,如果我的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; }
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号