nginx - 为什么 nginx add_headers 不能正常工作?

标签 nginx http-headers

我使用 Nginx 作为网络服务器。 这是我的 nginx.conf 文件:

server {

    listen 80;

    root /usr/share/nginx/html;
    index index.html index.htm;

    location ^~ /start/ {
        add_header 'Cross-Origin-Embedder-Policy' 'require-corp';
        add_header 'Cross-Origin-Opener-Policy' 'same-origin';
        try_files $uri $uri/ /index.html;
    }

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

当我在浏览器上打开此链接时,我在响应 header 部分的网络选项卡中看不到 header : https://example.com/start/629852d359d2a400034698a2

enter image description here

最佳答案

实际上 add_header 指令工作正常。很可能没有添加 header ,因为服务器上没有 /usr/share/nginx/html/start/629852d359d2a400034698a2 文件或目录,因此请求被重写为 /index.html 根据最后一个 try_files 指令参数,该参数又由您的 location/{ ... } 处理(因为新的 URI 不以 /start/ 前缀),并且该位置不设置任何附加 header 。


通常,如果这些 /start/ 前缀的 URI 可以是内部应用程序路由或外部 Assets 链接,则可以使用 map block 进行评估来解决所需的 header 值:

map $uri $add_policies {
    ~^/start/  1;
    # default value will be an empty string, unless specified explicitly
}
map $add_policies $embedder_policy {
    1  require-corp;
}
map $add_policies $opener_policy {
    1  same-origin;
}
server {
    ...
    location / {
        add_header Cross-Origin-Embedder-Policy $embedder_policy;
        add_header Cross-Origin-Opener-Policy $origin_policy;
        try_files $uri $uri/ /index.html;
    }
}

此解决方案基于 add_header 行为,如果提供的值为空字符串,则根本不会将指定的 header 添加到响应中。

但是,如果您确定应添加这些 header 的 URI 是应用程序路由而不是指向物理现有文件的链接,那么您还有一个选择:

server {
    ...
    location ^~ /start/ {
        set $embedder_policy require-corp;
        set $origin_policy same-origin;
        rewrite ^ /index.html last;
    }
    location / {
        add_header Cross-Origin-Embedder-Policy $embedder_policy;
        add_header Cross-Origin-Opener-Policy $origin_policy;
        try_files $uri $uri/ /index.html;
    }
}

此解决方案的性能应该会更高一些,因为它不需要(某种昂贵的)PCRE 库调用来执行正则表达式匹配操作。

更新

回顾我的答案,我发现使用rewrite ...break而不是rewrite ...last可以使最后的配置变得更加简单:

server {
    ...
    location ^~ /start/ {
        add_header Cross-Origin-Embedder-Policy require-corp;
        add_header Cross-Origin-Opener-Policy same-origin;
        rewrite ^ /index.html break;
    }
    location / {
        try_files $uri $uri/ /index.html;
    }
}

关于nginx - 为什么 nginx add_headers 不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72473889/

相关文章:

node.js - 使用 nginx + passenger 时如何在 node express 应用程序中查看 console.log 输出

php检测/获取发布请求的发件人url(或服务器)

http - X-Forwarded-Host header 的实际用法?

apache - Apache 的 Header 配置中的 "always"和 "onsuccess"有什么区别?

nginx - "worker_processes"指令不允许 nginx

facebook - URL 请求了 HTTP 重定向,但无法遵循。 - Facebook/Nginx 问题

node.js - TypeScript 在 Express 中添加自定义请求 header

php - 由于 GDPR,阻止所有欧盟访客

python - 使用/django和nginx解析URL

php - 如果我使用 PHP,如何解决 c10k 问题?