La directive traditionnelle add_header de Nginx ne fonctionne pas avec les réponses 4xx. Comme nous voulons toujours leur ajouter des en-têtes personnalisés, nous devons installer le module ngx_headers_more pour pouvoir utiliser la directive more_set_headers, qui fonctionne également avec les réponses 4xx.
sudo apt-get install nginx-extras
Ensuite, utilisez more_set_headers dans le fichier nginx.conf, j'ai collé mon exemple ci-dessous
server {
listen 80;
server_name example-site.com;
root "/home/vagrant/projects/example-site/public";
index index.html index.htm index.php;
charset utf-8;
more_set_headers 'Access-Control-Allow-Origin: $http_origin';
more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE, HEAD';
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Headers: Origin,Content-Type,Accept,Authorization';
location / {
if ($request_method = 'OPTIONS') {
more_set_headers 'Access-Control-Allow-Origin: $http_origin';
more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE, HEAD';
more_set_headers 'Access-Control-Max-Age: 1728000';
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Headers: Origin,Content-Type,Accept,Authorization';
more_set_headers 'Content-Type: text/plain; charset=UTF-8';
more_set_headers 'Content-Length: 0';
return 204;
}
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
access_log off;
error_log /var/log/nginx/example-site.com-error.log error;
sendfile off;
client_max_body_size 100m;
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors off;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
}
location ~ /\.ht {
deny all;
}
}