1. 程式人生 > >Nginx的alias的用法及與root的區別

Nginx的alias的用法及與root的區別

nginx root alias


先看官方文檔

http://nginx.org/en/docs/http/ngx_http_core_module.html#alias
http://nginx.org/en/docs/http/ngx_http_core_module.html#root

先看root的用法

location /request_path/image/
{
    root /local_path/image/;
}

nginx中配置

root@leco:/etc/nginx/sites-enabled# ls
default
root@leco:/etc/nginx/sites-enabled# egrep -v '#|^$' default 
server {
	listen 80 default_server;
	listen [::]:80 default_server;
	root /var/www/html;
	index index.html index.htm index.nginx-debian.html;
	server_name _;
        location /request_path/image/ {   
            root /local_path/image/;
        }
	location / {
		try_files $uri $uri/ =404;
	}
}
root@leco:/etc/nginx/sites-enabled# /etc/init.d/nginx reload
[ ok ] Reloading nginx configuration (via systemctl): nginx.service.

實際圖片路徑

root@leco:/local_path/image/request_path/image# pwd
/local_path/image/request_path/image
root@leco:/local_path/image/request_path/image# ls
1.png

這樣配置的結果就是當客戶端請求 /request_path/image/1.png 的時候,
Nginx把請求映射為/local_path/image/request_path/image/1.png

web訪問效果

技術分享圖片

再看alias的用法

location /request_path/image/ 
{    
    alias /local_path/image/;
}


這時候,當客戶端請求 /request_path/image/2.png 的時候,
Nginx把請求映射為/local_path/image/2.png
nginx配置

root@leco:/local_path/image# ls
2.png  request_path
root@leco:/local_path/image# pwd
/local_path/image
root@leco:/etc/nginx/sites-enabled# egrep -v '#|^$' default 
server {
	listen 80 default_server;
	listen [::]:80 default_server;
	root /var/www/html;
	index index.html index.htm index.nginx-debian.html;
	server_name _;
        location /request_path/image/ {
            alias /local_path/image/;
        }
	location / {
		try_files $uri $uri/ =404;
	}
}
root@leco:/etc/nginx/sites-enabled# /etc/init.d/nginx reload
[ ok ] Reloading nginx configuration (via systemctl): nginx.service.

圖片位置

root@leco:/local_path/image# pwd
/local_path/image
root@leco:/local_path/image# ls
2.png  request_path

web訪問效果

技術分享圖片

Nginx的alias的用法及與root的區別