Nginx

Nginx+PHP-FPM:讓php處理文件副檔名

  • November 25, 2019

我正在嘗試提供一個處理一些 RESTful URI 的 PHP 腳本並了解最終使用者需要哪種格式的數據,我將其作為 URI 中的副檔名進行處理,例如:

example.com/foo/bar.json?q=x&a=y --> data in ajax format
example.org/foo/bar.xml?q=x&a=y  --> data in xml format

我在我的開發機器中使用了 Apache httpd + modphp,它工作得很好,但是舞台伺服器使用了 CentOS + Nginx + PHP。在那裡,nginx 攔截並嘗試處理靜態 json 文件並返回 404。

如何防止 Nginx 處理某些文件類型(例如 json、xml)並讓 PHP 處理這些文件?

我的 Nginx 配置:

server {

 # listen [::]:443 ssl http2 accept_filter=dataready;  # for FreeBSD
 # listen 443 ssl http2 accept_filter=dataready;  # for FreeBSD
 # listen [::]:443 ssl http2 deferred;  # for Linux
 # listen 443 ssl http2 deferred;  # for Linux
 listen [::]:443 ssl http2;
 listen 443 ssl http2;

 # The host name to respond to
 server_name example.com;

 include h5bp/directive-only/ssl.conf;
 include ssl/conf/example.com;

 # Path for static files
 root /var/www/example.com/app/public;
 index index.php index.html index.htm;

 #Specify a charset
 charset utf-8;

 # Custom 404 page
 error_page 404 /404.html;

 # Include the basic h5bp config set
 include h5bp/basic.conf;

 # log settings
 access_log off;
 error_log  /var/log/www/example.com/nginx/error/error.log error;

 # turn off access logs and prevents logging
 # an error if robots.txt and favicon.ico are not found
 location = /favicon.ico { access_log off; log_not_found off; }
 location = /robots.txt  { access_log off; log_not_found off; }


 # check if a file or directory index file exists,
 # else pass the request to the index.php as a query parameter.
 location / {
   try_files $uri $uri/ /index.php?$query_string;
 }

 # handle execution of PHP files
 # set php5-fpm socket
 # tell NGINX to proxy requests to PHP FPM via the FCGI protocol
 location ~ \.php$ {
   fastcgi_split_path_info ^(.+\.php)(/.+)$;
   fastcgi_pass localhost:9003;
   fastcgi_index index.php;
   include fastcgi_params;
   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
   fastcgi_intercept_errors off;
   fastcgi_buffer_size 16k;
   fastcgi_buffers 4 16k;
   fastcgi_connect_timeout 300;
   fastcgi_send_timeout 300;
   fastcgi_read_timeout 300;
 }

 # block access to .htaccess files
 location ~ /\.ht {
   deny all;
 }

}

**更新:**它終於工作了,我把 json 相關的位置放在主要/位置,並將$script_file_namejson 相關的位置更改為靜態腳本名稱。感謝蒂姆。

告訴 PHP 將對 json 文件的請求傳遞給 PHP 解釋器。如果需要,您可以進行更精確的路徑匹配,例如只有“/api/scripts”目錄中的json文件,您只需要計算出正則表達式。

將您的 PHP 位置更改為此

location ~ \.(php|json)$ {

引用自:https://serverfault.com/questions/834333