Назад | Перейти на главную страницу

Nginx + PHP-FPM: позволить php обрабатывать расширения файлов

Я пытаюсь обслужить PHP-скрипт, который обрабатывает некоторые RESTful URI, и чтобы узнать, в каком формате конечному пользователю нужны данные, я обработал это как расширение в 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_name для местоположения, связанного с json, к имени статического скрипта. Спасибо Тиму.

Сообщите PHP, чтобы он передавал запросы на файлы json интерпретатору PHP. При необходимости вы можете сделать более точные совпадения путей, например, только файлы json в каталоге «/ api / scripts», вам просто нужно выработать регулярное выражение.

Измените свое местоположение PHP на это

location ~ \.(php|json)$ {