【问题标题】:Nginx add headers PHP FPM returns an errorNginx 添加标头 PHP FPM 返回错误
【发布时间】:2014-07-19 16:33:51
【问题描述】:

我正在使用带有 Nginx 和 PHP-FPM 的 Laravel 4 来为应用程序提供服务。

然而,该应用程序实现了一个 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;
    }
}

【问题讨论】:

  • > 如果响应代码等于 200、201、204、206、301、302、303、304 或 307,则将指定字段添加到响应标头。

标签: php nginx laravel-4 cors


【解决方案1】:

Nginx 的docs say 那个add_header

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

作为HttpHeadersMoreModule 的替代方法,您可以在 Laravel 中添加标头,方法如下:https://stackoverflow.com/a/17550224

【讨论】:

  • 谢谢@dened。添加一个 App::after(); Laravel 中的过滤器效果很好。
【解决方案2】:

其实解决方法很简单。 @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

【讨论】:

    猜你喜欢
    • 2017-11-19
    • 2013-09-28
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 2011-04-06
    • 1970-01-01
    相关资源
    最近更新 更多