Nginx의 서버 이름을 기반으로 단일 위치 변경

Nginx의 서버 이름을 기반으로 단일 위치 변경

내 구성에 50개의 위치 항목이 있는 서버 항목이 있습니다. 한 위치를 제외하고 동일한 구성으로 내 서버에 다른 도메인을 정의해야 합니다.

예를 들어 나는

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;
        }
    }

가능하다면 모든 구성을 조각으로 추출한 다음 이를 2개의 서버 항목에 포함시키는 것을 피하고 싶습니다. 하나는 기본 도메인이고 다른 하나는 하위 도메인입니다.

내가 복사한 코드가 작동하지 않는다는 것을 알고 있으며 읽어보았습니다.만약에 악하다

뭔가를 암시하는 것

    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

map및 문을 사용하면 더 깔끔한 솔루션을 얻을 수 있습니다 try_files.

예를 들어:

map $host $robots {
    ~^\w+\.\w+\.\w+$ /robots_disallow.txt;
    default          /robots.txt;
}

server {
    ...

    location = /robots.txt {
        root /srv;
        try_files $robots =404;
    }

    ...
}

보다이 문서자세한 내용은.

관련 정보