這篇會簡單說明 nginx conf CORS header 的設定 和 map 的用法
(跨來源資源共用(Cross-Origin Resource Sharing (CORS))
一般要開放 CORS 請求,會另外設定 header
最常見的 nginx conf 範例…
server {
.
.
.
# add CORS header for easier test
add_header 'Access-Control-Allow-Origin' * always;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, DELETE';
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With';
.
.
.
}
上述語法會開放所有網站,所有 method 都可以進行 cors
但這樣非常不安全~
一般來說~ 開放的愈少、給的愈少網站服務就愈安全
通常會指定 domain / origin,只開放指定的網站可以進行 cors
指定一個網域~
add_header 'Access-Control-Allow-Origin' 'https://cola.workxplay.net' always;
但如果有多個網站也想開放呢
e.g.
https://cola.workxplay.net
https://bear.workxplay.net
https://pamcy.net/
這時可以透過 Nginx conf 裡的 map 指定多個 domain
map $http_origin $cors_origin {
default "";
"~https://cola.workxplay.net" "$http_origin";
"~https://bear.workxplay.net" "$http_origin";
"~https://pamcy.net" "$http_origin";
}
.
.
.
server {
.
.
.
# add CORS header for easier test
add_header 'Access-Control-Allow-Origin' $cors_origin always;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, DELETE';
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With';
.
.
.
網路上可以找到更多的範例
只是範例和教學常常忘了註明
map 必須在 server {} 範圍之外
造成設定一直不成功