我的 Nginx 配置中有一个位置块,如下所示:
location ~* "/Record\.([A-Za-z0-9]{4,6})$" {
add_header Link "https://doi.org/xx.xxxxx/Record.$1; rel='cite-as'";
proxy_http_version 1.1;
if ($http_accept = 'application/ld+json') {
rewrite "^/Record\.([A-Za-z0-9]{4,6})" /content_negotiation/jsonld/Record.$1 break;
proxy_pass https://api.example.org;
}
root /home/example.org/client/dist;
try_files $uri $uri/ /index.html;
}
这应该做两件事:
- 如果有人请求 ld+json,它会代理请求到我们的 API 并将其返回给他们。
- 如果他们发出 HEAD 请求(例如使用
curl -I
),则应在标题中添加“cite-as”链接。
上述函数中的第二个仅在我传递 ld+json 请求参数时才有效。例如curl -I 'https://example.org/Record.abc123'
:
server: nginx
date: Wed, 27 Sep 2023 10:32:28 GMT
content-type: text/html; charset=utf-8
content-length: 1046
last-modified: Thu, 21 Sep 2023 13:28:40 GMT
etag: "650c4508-416"
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
accept-ranges: bytes
但跑步却curl -I -H 'Accept: application/ld+json' 'https://example.org/Record.abc123
带来:
server: nginx
date: Wed, 27 Sep 2023 10:33:41 GMT
content-type: application/ld+json; charset=utf-8
status: 200 OK
cache-control: max-age=0, private, must-revalidate
referrer-policy: strict-origin-when-cross-origin
x-permitted-cross-domain-policies: none
x-xss-protection: 0
maintenance: false
x-request-id: e1601dda-9833-4633-860e-327a664582f9
x-download-options: noopen
x-frame-options: SAMEORIGIN
x-runtime: 0.029898
x-content-type-options: nosniff
read-only: false
x-powered-by: Phusion Passenger(R) 6.0.15
access-control-allow-origin: *
access-control-allow-methods: GET, POST, PUT, DELETE, OPTIONS, HEAD
access-control-allow-headers: DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,X-Client-Id,Authorization,Access-Control-Allow-Origin
access-control-expose-headers: Content-Length,Content-Range,Maintenance,Read-Only
link: https://doi.org/xx.xxxxx/Record.9kahy4; rel='cite-as'
...其中很多(例如访问控制允许方法)来自 API。
有人能解释为什么我没有得到link
带有默认curl -I
请求的字段吗?
答案1
最终,我设法把一切拼凑起来。
set $special_headers false;
set $special_link '';
location ~* "/Record\.([A-Za-z0-9]{4,6})$" {
set $special_headers true;
set $special_link "https://doi.org/xx.xxxxxx/$1; rel='cite-as'";
# Api stuff if the user wants ld+json
# try_files otherwise
}
location =/index.html {
if ($special_headers = true) {
add_header Link $special_link;
}
}