nginx location配置中的root、alias用法区别之域名二级目录绑定其他网页目录
这两天搭建了两个同类型的网站,我这里就说网站a和网站b吧,这里也假设他们的目录对应为/home/wwwroot/a、/home/wwwroot/a。后面想了一下为了维护方便,决定把b的网站目录绑定到a域名的二级目录,即:a.com/b/。
这里可能有些朋友要问,为什么不直接把b目录移动到a的目录之下。我没有这么做是因为b的网页文件是一个配套的程序生成的,而我移动文件,需要把配套的程序和配置文件一起移动到a目录之下,这样等于把源程序、配置文件、以及其他目录公开暴露无疑,虽然可以通过通过配置nginx的方式屏蔽下载源文件及屏蔽访问指定的目录,但还是略显麻烦。
所以在无奈之下,必须尝试原先设想的的思路是否可行,下面我就记录一步一步修改配置文件的过程,
原来的网页配置文件:
server
{
listen 80;
#listen [::]:80;
server_name a.com ;
index index.html index.htm index.php default.html default.htm default.php;
root /home/wwwroot/a;
}
添加设想的配置1:
server
{
listen 80;
#listen [::]:80;
server_name a.com ;
index index.html index.htm index.php default.html default.htm default.php;
root /home/wwwroot/a;
location /b {
root /home/wwwroot/b;
}
}
配置生效后,直接访问a.com/b,页面直接显示404。
紧接着参考了笛声博客的《Nginx的location规则迷之匹配》这篇文章后,考虑到可能是location的优先级问题,直接在location处添加=提升优先级到最高,修改配置文件为:
server
{
listen 80;
#listen [::]:80;
server_name a.com ;
index index.html index.htm index.php default.html default.htm default.php;
root /home/wwwroot/a;
location = /b {
root /home/wwwroot/b;
}
}
配置生效后,访问a.com/b直接显示404,域名后面添加横杆后,即:a.com/b/,成功把域名的二级目录绑定到其他网页目录。
紧接着在配置文件中尝试alias替换root:
server
{
listen 80;
#listen [::]:80;
server_name a.com ;
index index.html index.htm index.php default.html default.htm default.php;
root /home/wwwroot/a;
location /b {
alias /home/wwwroot/b;
}
}
配置生效后,打开a.com/b :正常,打开a.com/b/ :正常。
现在通过表格对比一下nginx location配置中的root、alias在域名二级目录绑定其他网页目录的优缺点及用法区别:
alias | root | |
---|---|---|
优点 | 不用提升优先级,没有root第二个缺点 | 暂不清楚 |
缺点 | 暂不清楚 | 1.root需提升在location中的优先级 2.域名二级目录后面加/ 才能打开 |
用法 | 用在location{}之内 | 用在location{}之内 |
区别 | 用在location{}之内不可单独使用 | 用在location{}之内可单独使用,如用在server{}之内 |