繁体   English   中英

根据server_name更改NGINX根目录位置

[英]Change NGINX root location depending on server_name

我正在尝试使用它的变量根据server_name指定根位置。 我的配置如下:

server {
    listen       80;
    server_name  ~^(host1|host2)\.example\.com$;

    access_log  /var/log/nginx/hosts_access.log main;
    error_log   /var/log/nginx/hosts_error.log;

    if ($server_name = host1.example.com) { 
        set $root_path /var/www/host1; 
    }

    if ($server_name = host2.example.com) { 
        set $root_path /var/www/host2; 
    }

    root $root_path;

    location = /robots.txt { return 200 "User-agent: *\nDisallow: /\n"; }

    location / {
        index  index.html;
        try_files $uri $uri/ /index.html =404;
    }

    location ~* \.(jpe?g|png|gif|ico)$ {
        expires 1h;
        access_log off;
    }

    location ~ /\.(ht|svn|git) {
        deny all;
    }
}

实际上,我意识到无法正确设置此配置,但是nginx使用nginx -t命令找不到任何错误。 是否可以通过这种方式进行配置? 我应该使用$http_host/$host代替$server_name作为变量吗?

您可以使用正则表达式中的变量来更改根。

server {
    listen 80;
    server_name     ~^(?<subdomain>.+)\.example\.com$;

    root /var/www/$subdomain;
    ...
}

如果在正则表达式中命名变量,则可以在整个服务器块中使用它。 这比if语句容易得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM