【问题标题】:Change NGINX root location depending on server_name根据 server_name 更改 NGINX 根位置
【发布时间】:2018-01-23 14:55:29
【问题描述】:

我正在尝试根据 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命令有任何错误。 i是否可以这样进行配置?我应该使用$http_host/$host 而不是$server_name 作为变量吗?

【问题讨论】:

    标签: linux nginx configuration


    【解决方案1】:

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

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

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

    【讨论】:

    • 再次感谢您的回答,我是这样做的:server_name ~^(?&lt;subdomain&gt;(host1|host2))\.example\.com$; 一切正常!
    猜你喜欢
    • 1970-01-01
    • 2020-03-17
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 2017-08-29
    相关资源
    最近更新 更多