在Nginx中,根据服务器名称更改单个位置

分享于 

2分钟阅读

互联网

  繁體

问题:

例如我有


server {



 # the port your site will be served on


 # the domain name it will serve for


 listen 443 ssl;


 server_name example.com sudomain.example.com;



 ssl_certificate /etc/loc/fullchain.pem; # managed by Certbot


 ssl_certificate_key /etc/loc/privkey.pem; # managed by Certbot



 proxy_set_header X-Forwarded-Proto https;



 location /static/ {


 root /srv/sites/example;


 }


... # many more location defenition



}



需要做的是


 location /robots.txt {


 if ($host ~ ^w+.w+.w+$) { 


 # subdomains


 alias /srv/robots_disallow.txt;


 } else {


 alias /srv/robots.txt;


 }


 }




 error_page 418 = @disallow_robots;


 location /robots.txt {


 alias /srv/robots.txt;



 if ($host ~ ^w+.w+.w+$) { 


 # subdomains


 return 418;


 }


 }



 location @disallow_robots {


 alias /srv/robots_disallow.txt;


 }



the "alias" directive cannot be used inside the named location


答案1:

你使用maptry_files语句实现更清晰的解决方案。

例如:


map $host $robots {


 ~^w+.w+.w+$ /robots_disallow.txt;


 default /robots.txt;


}



server {


 ...



 location = /robots.txt {


 root /srv;


 try_files $robots =404;


 }



 ...


}





Server  BASE  LOC  SIN  Nginx  本地