nginx php header,nginx add_header不起作用

两个问题。

一个是,nginx只处理最后一个add_header。 因此,如果你在服务器上下文中有一个add_header,那么另一个在location嵌套上下文中,它将只处理location上下文中的add_header指令。 只作用最深层的上下文。

第二个问题是,location/ {}块实际上已经把请求发送到另一个location〜*(\ .php)$ block(因为它会重写所有请求到index.php)。 所以,我第一个location的add_header指令是无用的,我把指令加到所有的php location它才正常。

最后,这是我的配置,允许在一个名为Laravel的MVC框架CORS

server {

root /path/to/app/public;

index index.php;

server_name test.dev;

# redirection to index.php

location / {

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

}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

location ~ \.php$ {

fastcgi_split_path_info ^(.+\.php)(/.+)$;

# NOTE: You should have “cgi.fix_pathinfo = 0;” in php.ini

# With php5-fpm:

fastcgi_pass unix:/var/run/php5-fpm.sock;

fastcgi_index index.php;

include fastcgi_params;

# cors configuration

# whitelist of allowed domains, via a regular expression

# if ($http_origin ~* (http://localhost(:%5B0-9%5D+)?)) {

if ($http_origin ~* .*) { # yeah, for local development. tailor your regex as needed

set $cors “true”;

}

# apparently, the following three if statements create a flag for “compound conditions”

if ($request_method = OPTIONS) {

set $cors “${cors}options”;

}

if ($request_method = GET) {

set $cors “${cors}get”;

}

if ($request_method = POST) {

set $cors “${cors}post”;

}

# now process the flag

if ($cors = ‘trueget’) {

add_header ‘Access-Control-Allow-Origin’ “$http_origin”;

add_header ‘Access-Control-Allow-Credentials’ ‘true’;

}

if ($cors = ‘truepost’) {

add_header ‘Access-Control-Allow-Origin’ “$http_origin”;

add_header ‘Access-Control-Allow-Credentials’ ‘true’;

}

if ($cors = ‘trueoptions’) {

add_header ‘Access-Control-Allow-Origin’ “$http_origin”;

add_header ‘Access-Control-Allow-Credentials’ ‘true’;

add_header ‘Access-Control-Max-Age’ 1728000; # cache preflight value for 20 days

add_header ‘Access-Control-Allow-Methods’ ‘GET, POST, OPTIONS’;

add_header ‘Access-Control-Allow-Headers’ ‘Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since’;

add_header ‘Content-Length’ 0;

add_header ‘Content-Type’ ‘text/plain charset=UTF-8’;

return 204;

}

}

error_log /var/log/nginx/test.dev.error.log;

access_log /var/log/nginx/test.dev.access.log;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值