Nginx root和alias的区别

前言

这是我的第一篇技术博客,希望可以记录自己的学习过程,还有分享经验。

问题:使用了nginx作为静态文件服务器,写入了如下配置:

server{
  listen 80; #监听的端口
  server_name  ********;   #监听的ip和端口

  location / {
    root /usr/share/nginx/html;
    index index.html;
  }

  # 静态文件服务器
  location /downloads {
    root /opt/product/wechat/downloads;
    autoindex on;
  }
}

放入/opt/product/wechat/downloads/1.jpeg后,发现访问http://********/downloads/1.jpeg,服务器返回404错误。

查看nginx官方文档(https://docs.nginx.com/nginx/admin-guide/web-server/serving-static-content/),原来这是由于root和alias的分别所致:

root:

The root directive specifies the root directory that will be used to search for a file. To obtain the path of a requested file, NGINX appends the request URI to the path specified by the root directive.

root指令指明了查找文件的根目录。Nginx拼接root的根目录和请求URI,来得到文件的路径。

alias:

Alias就是将uri部分替代为alias的目录名。Alias指令的路径,最后必须添加/

最终配置:

server{
  listen 80; #监听的端口
  server_name  ********;   #监听的ip和端口

  location / {
    root /usr/share/nginx/html;
    index index.html;
  }

  # 静态文件服务器
  location /downloads {
    alias /opt/product/wechat/downloads/;
    autoindex on;
  }
}

终于可以成功访问!

猜你喜欢

转载自www.cnblogs.com/JansenGao/p/9028824.html
今日推荐