我的配置上有一個伺服器條目,大約有 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;
}
}
如果可能的話,我想避免將所有配置提取到一個片段中,然後將其包含在兩個伺服器條目中,一個用於主域,一個用於子網域。
我知道我複製的程式碼不起作用,並且我已閱讀如果是邪惡的
這暗示了一些事情
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;
}
...
}
看這個文件了解詳情。