一聚教程网:一个值得你收藏的教程网站

热门教程

nginx alias root 和 location 指向的教程

时间:2022-06-30 18:23:25 编辑:袖梨 来源:一聚教程网

虚拟服务器可拥有一个宿主目录和任意数量的其它目录,这些其它目录通常被称为虚拟目录。

nginx没有虚拟目录的说法,因为nginx本来就根据目录设计并工作的。如果要把虚拟目录强硬插上一个虚拟目录的说法,那只有alias标签比较像。还有一个和alias相似的标签root,它们之间有何区别?

最基本的区别

alias 指定的目录是准确的, 作用可以理解为linux的 ln,给location指定一个目录。

root 指定目录的上级目录,并且该上级目录要含有locatoin指定名称的同名目录。

alias使用注意

使用alias时,目录名后面一定要加”/“。

使用alias标签的目录块中不能使用rewrite的break。

alias在使用正则匹配时,必须捕捉要匹配的内容并在指定的内容处使用。

alias只能位于location块中

例子

location /abc/ {
    alias /home/html/abc/;
}

在这段配置下,http://test/abc/a.html 就指定的是 /home/html/abc/a.html。这段配置亦可改成使用root标签:

location /abc/ {
    root /home/html/;
}

这样,nginx就会去找/home/html/目录下的abc目录了,得到的结果是相同的。但是,如果我把alias的配置改成

location /abc/ {
    alias /home/html/def/;
}

那么nginx将会直接从/home/html/def/取数据,例如访问http://test/abc/a.html指向的是 /home/html/def/a.html

这段配置还不能直接使用root配置,如果非要配置,只有在/home/html/下建立一个 def->abc的软link(快捷方式)了。

一般情况下,在location /中配置root,在location /other中配置alias是一个好习惯。

alias fast-cgi

nginx在处理php脚本时,需要传递给fastcgi才能处理,下面是fast-cgi无法工作的配置

server {
    listen      80;
    server_name  pwta;
    root html;

    location /test/{
        alias html/test/;
        autoindex on;
    }
    location ~ .php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

通过上面的配置, 我们发现, 访问/test/a.php, php脚本并没有作用。为什么呢?答案在下面:

Adding alias will effectively overwrite the $document_root to whatever is the alias. Note that it will not affect $fastcgi_script_name or $request_filename. Using the new $document_root together with regex matching the file name, resolves to the script file

针对上面的配置我们要改成这样:

server {
listen      80;
server_name  pwta;
index index.html index.php;
root html;

location /test/ {
    alias html/test/;
}

location ~  ^/test/(.+.php)$ { ### This location block was the solution
    alias html/test/;    
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$1;
    include fastcgi_params;
}

 location ~ .php$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
}

重启nginx,php文件解析生效

热门栏目