我刚刚为我华丽的新网站创build了一个API,并希望返回错误响应与相关的状态代码。 但是,我已经configuration了正常的path来使用error_page指令,我不想删除错误页面。
我有一个index.php文件,处理API和网站的所有请求。
server { listen 80; listen 443 ssl http2; server_name ~^(.+)\.flashy\.local$; root "/home/vagrant/flashy/core/www"; index index.html index.htm index.php; charset utf-8; error_page 400 /error/error-400.html; error_page 403 /error/error-403.html; error_page 404 /error/error-404.html; error_page 500 501 /error/error-500.html; error_page 502 503 504 /error/error-503.html; location ~ ^/error/error-(403|404|500|503)\.html$ { internal; root /home/vagrant/flashy; } location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_buffer_size 16k; fastcgi_buffers 4 16k; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; fastcgi_intercept_errors on; } location / { try_files $uri $uri/ /index.php?$query_string; } access_log off; error_log /var/log/nginx/~^(.+)\.flashy\.local$-error.log error; sendfile off; client_max_body_size 100m; location ~ /\.ht { deny all; } ssl_certificate /etc/nginx/ssl/~^(.+)\.flashy\.local$.crt; ssl_certificate_key /etc/nginx/ssl/~^(.+)\.flashy\.local$.key; }
现在,你们中的一些人可能想知道? 我试过了什么?
我尝试添加一个/api/位置来将fastcgi_intercept_errors参数更改为closures,但它似乎重新设置,因为它将打到一个PHP文件。
location /api/ { fastcgi_intercept_errors off; try_files $uri $uri/ /index.php?$query_string; }
我也尝试了一个if语句,看看是否可以匹配这个基于内容标题。 不过,如果可能,我不想使用if语句,因为这似乎是一个坏主意。
... fastcgi_send_timeout 300; fastcgi_read_timeout 300; if ($content_type != "application/json") { fastcgi_intercept_errors on; } } ...
我的问题与这个问题非常相似,但它也没有答案。 希望我的问题稍有不同,也许更好地解释?
如何closures特定apipath的fastcgi_intercept_errors?
您将需要在API的URI的新location复制FastCGIconfiguration。 大多数fastcgi指令都可以被移动到server模块中,并被location ~ \.php$块和新的location模块所inheritance。 详情请参阅此文件 。
完全匹配的location块的优先级最高,因此本例中块的顺序并不重要(详情请参阅此文档 ):
include fastcgi_params; fastcgi_param SCRIPT_FILENAME $request_filename; fastcgi_buffer_size 16k; fastcgi_buffers 4 16k; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; location = /api/api.php { fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; } location ~ \.php$ { fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; fastcgi_intercept_errors on; }
fastcgi_split_path_info和fastcgi_index指令与您的configuration无关。