Nginx配置跨域处理

162 阅读1分钟
server {

    server_name cli.test;
    
    root /var/www/cli.test/public;

    add_header X-Content-Type-Options "nosniff";
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";

    add_header Access-Control-Allow-Credentials "true";
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET,POST,OPTIONS";
    add_header Access-Control-Allow-Headers "*";

    location / {
	try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
	
        set $cors "";

        if ($request_method = "OPTIONS") {
            set $cors "O";
	}

	if ($http_origin) {
            set $cors "${cors}K";
	}

	if ($cors = "OK") {
            return 200;
	}

        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;

        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        
	include snippets/fastcgi-php.conf;

	fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
	fastcgi_param DOCMENT_ROOT $realpath_root;

        internal;
    }

    location ~ \.php$ {
        return 404;
    }

    error_log /var/log/nginx/cnsl_herrywatch_test_error.log;
    access_log /var/log/nginx/cnsl_herrywatch_test_access.log;
}