Nginx proxy_pass 路径末尾加不加 / 的问题

今天在配置nginx转发的时候遇到了一个问题:proxy_pass路径末尾加不加 / 差别很大。下边两种配置跳转的路径是不一样的。

# nginx配置
server {
    listen 8088;
    server_name localhost; 
    
    location ^~ /test/ {
        proxy_pass http://localhost:8000/; # 带 /
    }
	
    location ^~ /test/ {
        proxy_pass http://localhost:8000; # 不带 /
    }
}

在任意目录下运行 puer (启动一个文件服务器,默认8000端口,nginx上边的配置会代理过来)

# 文件服务器根目录
├── test
│   ├── index.html
├── index.html
├── rewrite
├── ├── index.html

我们在浏览器中输入 http://localhost/test/index.html

  1. 带/实际访问的是 http://localhost:8000/index.html (相当于根或绝对路径,不会在代理路径后拼接locaiton中匹配规则的路径,比如上边的test)
  2. 无/实际访问的是 http://localhost:8000/test/index.html (相当于相对路径,会在代理路径后拼接locaiton中匹配规则的路径)

当然,我们可以使用 rewrite 来实现 proxy_pass后加 / 的效果

# 实际访问的是 `http://localhost:8000/index.html`
location ^~ /test/ {
    rewrite /test/(.+)$ /$1 last;
}

同样我们也可以改为如下:

# 实际访问的是 `http://localhost:8000/rewrite/index.html`
location ^~ /test/ {
    rewrite /test/(.+)$ /rewrite/$1 last;
}
rewrite 和 proxy_pass执行顺序
  • 执行server下的rewrite
  • 执行location匹配
  • 执行location下的rewrite
rewrite 和 proxy_pass 跳转域名区别
  • rewrite 同一域名跳转
  • proxy_pass 任意域名跳转

参考资料:

原文地址:https://www.cnblogs.com/hanshuai/p/14437234.html