nginx根据子路径添加头

时间:2018-11-08 12:15:56

标签: nginx

我有以下内容:

location ~ \.php$ {
    try_files $uri =404;

    include fastcgi_params;

    fastcgi_pass unix:/var/run/php-fpm.sock;
    ...
    if ($host = "www.domain.tld") {
        add_header Access-Control-Allow-Origin "https://site.domain.tld";
    }

什么是更改标头的正确方法,以便如果路径包含/api,则标头变为:

add_header Access-Control-Allow-Origin "https://docs.domain.tld";

非常感谢任何建议

1 个答案:

答案 0 :(得分:0)

您最好创建2个不同的位置和share common proxy config and include as-needed

/etc/nginx/proxy.conf

try_files $uri =404;
include fastcgi_params;
fastcgi_pass unix:/var/run/php-fpm.sock;
...

您的主机配置文件

location ~ \.php$ {
    include /etc/nginx/proxy.conf;
    ...
    if ($host = "www.domain.tld") {
        add_header Access-Control-Allow-Origin "https://site.domain.tld";
    }
}
location ~ .*/api.*.php$ {
    include /etc/nginx/proxy.conf;
    ....
    add_header Access-Control-Allow-Origin "https://docs.domain.tld";
    ....
}

此外,这也可以通过在$ uri变量上使用if语句来解决。但是 If Is Evil 。 也就是说,您应该避免在$ host上使用if语句,它是bad practice