nginx路径及分隔符小结

nginx路径分隔符配置(斜杠'/')参考:https://www.jianshu.com/p/c751250a5112

1.静态代理
location ${path} {
    root html; # 会将${path}一起加入到代理的(/html/${path})路径中
    alias html; # 不会将${path}一起加入到代理的(html/)路径中
}
2.动态代理
listen 80;
server_name localhost;
location ${path} {
    proxy_pass  ${destination};
}
目的:http://localhost/${path}/xxx => ${destination}/xxx
规则:nginx截取请求的URL对http://localhost/${path}进行全替换,因此${path}与${destination}是否会使用"/"结尾会影响需要代理转发的目标路径
结论:
一.当${destination}为IP:PORT(不含URL路径)时
    1.如果${destination}不使用"/"结尾,无论${path}是否使用"/"结尾,代理转发的目标路径都会加上${path}即:http://localhost/${path}/xxx => ${destination}/${path}/xxx
    2.如果${destination}使用"/"结尾,使用全替换的方式
        当${path}不使用"/"结尾,${destination}使用"/"结尾,会出现双斜杠问题,导致URL错乱,应避免
        location /api {
           proxy_pass http://localhost:9527/;
        }
        # http://localhost/api/xxx -> http://localhost:9527//xxx
        # http://localhost/api5/xxx -> http://localhost:9527/5/xxx
二.当${destination}为IP:PORT/PATH时,均使用全替换的方式
    当${path}不使用"/"结尾,${destination}使用"/"结尾,会出现双斜杠问题,导致URL错乱,应避免
    location /api {
       proxy_pass http://localhost:9527/ok/;
    }
    # http://localhost/api/xxx -> http://localhost:9527/ok//xxx
    # http://localhost/api5/xxx -> http://localhost:9527/ok/5/xxx

nginx路径匹配顺序参考:https://www.jianshu.com/p/38810b49bc29

你可能感兴趣的:(nginx路径及分隔符小结)