Nginx添加标头PHP FPM返回错误

时间:2014-05-30 01:39:36

标签: php nginx laravel-4 cors

我使用Laravel 4和Nginx以及PHP-FPM来为应用程序提供服务。

该应用程序实现了一个API,但我已经向Nginx添加了一些相当开放的CORS规则,这些规则似乎工作正常。

每当应用程序抛出错误时,Nginx似乎都不会将标头添加为响应的一部分。有没有办法在不必安装更多标头扩展名的情况下强制执行此操作?

我的配置如下:

server {
    listen 80;
    server_name mediabase.local;
    root /home/vagrant/mediabase/public;

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;

    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET, OPTIONS, POST, HEAD, DELETE, PUT";
    add_header Access-Control-Allow-Headers "Authorization, X-Requested-With, Content-Type, Origin, Accept";
    add_header Access-Control-Allow-Credentials "true";
    add_header Access-Control-Max-Age: 86400;


    }

    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/mediabase.local-error.log error;

    error_page 404 /index.php;

    sendfile off;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;

    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET, OPTIONS, POST, HEAD, DELETE, PUT";
    add_header Access-Control-Allow-Headers "Authorization, X-Requested-With, Content-Type, Origin, Accept";
    add_header Access-Control-Allow-Credentials "true";
    add_header Access-Control-Max-Age: 86400;

    }

    location ~ /\.ht {
        deny all;
    }
}

2 个答案:

答案 0 :(得分:3)

Nginx的docs say add_header

  

将指定字段添加到响应标头中,前提是   响应代码等于200,201,204,206,301,302,303,304或307

作为HttpHeadersMoreModule的替代方案,您可以在Laravel中添加标题,以下是完成此操作的方法:https://stackoverflow.com/a/17550224

答案 1 :(得分:0)

实际上,解决方案非常简单。 @dened是正确的,但是在这里如何处理我从这里https://coderwall.com/p/wprykg/cors-with-nginx-for-401-404-501-and-any-other-http-status

窃取的问题
add_header 'Access-Control-Allow-Origin' * always;

Javis V. Pérez表示敬意