2

Nginx配置中Root和Alias分不清?本文3分钟帮你解惑

 1 year ago
source link: https://server.51cto.com/article/721897.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Nginx配置中Root和Alias分不清?本文3分钟帮你解惑

作者:wljslmz 2022-11-02 17:57:36
NGINX 是全球最受欢迎的 Web 服务器之一,用于反向代理和负载均衡,还提供 HTTP 服务器功能,主要是为实现最大性能和稳定性而设计的。

Nginx在配置映射路径的时候,有时候看到的是root,有时候看到的是alias,这两个有什么区别?本文笔者将带大家详细了解一下。

什么是Nginx

NGINX 是全球最受欢迎的 Web 服务器之一,用于反向代理和负载均衡,还提供 HTTP 服务器功能,主要是为实现最大性能和稳定性而设计的。

Ubuntu关于Nginx的命令:

1、安装Nginx:

apt-get install nginx
84f268f86f848652ad5929e355ddd576eac0ef.png

2、查看Nginx运行状态:

systemctl status nginx

3、启动Nginx:

systemctl start nginx

4、停止Nginx:

systemctl stop nginx

5、重启Nginx:

temctl restart nginx

Nginx 的核心设置主要在 Nginx config 文件中进行配置,下面我们来看下配置中root和alias的区别。

Nginx root指令

root 指定文件根文件夹对应的/URL 路径,例如,如果你的 Root 指令是 /var/www/wljslmz.cn,那么当用户请求 /static/img/wljslmz.png 时,Nginx 将为他们提供/var/www/wljslmz.cn/static/img/wljslmz.png

换句话说,将 URL 路径附加到根位置来形成要提供的最终文件路径。

举个例子:

server {
    server_name https://www.wljslmz.cn;
    listen 443;
 
    index index.html;
    root /var/www/wljslmz.cn;
 
    location / {
        try_files $uri $uri/ =404;
    }
 
    location ^~ /img {
        root /var/www/static;
        try_files $uri $uri/ =404;
    }
}

如上配置,当用户访问https://www.wljslmz.cn/img/wljslmz.png时,会找到/var/www/static/img/wljslmz.png图片。

Nginx alias指令

alias 指令就是将 URL 重新映射到根位置以外的其他目录,它对于从不同目录提供静态文件很有用,例如,如果位置 /static/ 的别名是 /var/www/static/images,那么当用户请求 /img/wljslmz.png 时,Nginx 将在 /var/www/static/images 中查找该文件。

我们同样举个例子:

server {
    server_name https://www.wljslmz.cn;
    listen 443;
 
    index index.html;
    root /var/www/wljslmz.cn;
 
    location / {
        try_files $uri $uri/ =404;
    }
 
    location ^~ /img {
        alias /var/www/static/images/;
        try_files $uri $uri/ =404;
    }
}

如上配置,当用户访问https://www.wljslmz.cn/img/wljslmz.png时,会找到/var/www/static/images/wljslmz.png图片。

我们要注意:对于alias指定的文件夹,官方虽然没有强制要求加“/”,但是我们最好加上,以便阅读。

root 和 alias 区别

root读取的时根目录。可以在server或location指令中使用。

alias只能在location指令中使用。

两者何时用?

  • 如果位置与别名路径的末尾匹配,最好使用root。
  • 如果从与 root 指定的目录不同的位置读取数据时,最好使用alias。

Nginx在Web开发中出场率非常高,本文主要讲解了什么时Nginx,重点对比了Nginx配置中root和alias指令的用法和区别,希望本文对您有所帮助.

责任编辑:武晓燕 来源: 今日头条

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK