вторник, 24 сентября 2013 г.

Конфигурация Nginx + PHP + FastCGI для Magento

Не так давно пришлось оптимизировать сервер у заказчика. Нужно было заменить Apache на Nginx. 
На официальном форуме можно найти примеры конфигурации, например
http://www.magentocommerce.com/boards/viewthread/7931/ ,
однако использование rewrite для таких случаев всячески порицается разработчиком сервера.

Замечания

* Процесс сборки nginx и php описан на офсайтах
* Предполагается, что php с поддержкой fast-cgi настроен и работает на
127.0.0.1:8888, а nginx на 127.0.0.1:80
* Папка, в которой лежат файлы Magento: /home/alex/www/server.com/
* Так как Nginx работает с php напрямую, а не через связку с Apache, следует
обратить особое внимание
  на директивы для php, которые идут в .htaccess из стандартной поставки magento. Nginx 
  не обрабатывает директивы из .htaccess и поэтому их нужно перенести в php.ini. 
  У меня, например, перестала работать загрузка картинок к товарам, пока не добавил suhosin.session.cryptua off в php.ini.
* Предполагается, что в Magento настроены ЧПУ

Ниже привожу свою конфигурацию. Дополнения и комментарии всячески приветствуются.

    server {
    listen 127.0.0.1:80;
    server_name server.com;
    #Включаем сжатие
    gzip on;
    #gzip_comp_level 9;
    gzip_min_length 1000;
    gzip_proxied any;
    gzip_types text/plain application/xml text/html text/css text/js application/x-javascript;
    # Важно!!!! Ниже должна быть указана папка в которой лежит код Magento
    root /home/alex/www/server.com/;

    location / {
    index index.php;
    error_page 404 = @magento;
    }
    # Фикс для js
    location /js/ {
    index index.php;
    error_page 404 = @magento_js;
    }
    # Фикс для случая, когда используется расширение FOOMAN_Speedster.
    location ^~ /minify/ {
    rewrite ^/minify/([^/]+)(/.*.(js|css))$ /lib/minify/m.php?f=$2&d=$1 last;
    break;
    }

    location @magento {
    # Если fastcgi_params лежит по другому пути то заменить на свой
    include /etc/nginx/fastcgi_params; #Важно !!!!
    fastcgi_pass 127.0.0.1:8888;
    fastcgi_param SCRIPT_FILENAME $document_root/index.php; #Важно !!!
    }

    location @magento_js {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass 127.0.0.1:8888;
    fastcgi_param SCRIPT_FILENAME $document_root/js/index.php;
    }
    location ~ .php$ {
    index index.php;
    include /etc/nginx/fastcgi_params;
    fastcgi_pass 127.0.0.12:8888;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ~* \.(jpg|gif|png|css|js|jpeg|ico)$ {
    if (-f $request_filename) {
    access_log off;
    expires 7d;
    }

    }

После такой настройки плагин YSlow дает сайту уровень B по скорости. Если очень постараться и
 вынести всю статику на отдельный поддомен, то можно еще ускориться. 
 
Источник 

Magento + Nginx

This config currently seems to work for the <1 .4="" p="" versions="">
server {
  server_name example.com;
  root /var/www/vhost/example.com/htdocs;
  access_log /var/log/nginx/example.com.access.log main;
  index index.php;
 
  location / {
    try_files $uri $uri/ /index.php?$args; 
  }
 
  # set a nice expire for assets
  location ~* "^.+\.(jpe?g|gif|css|png|js|ico|pdf|zip|tar|t?gz|mp3|wav|swf)$" {
    expires    max;
    add_header Cache-Control public;
  }
 
  # the downloader has its own index.php that needs to be used
  location ~* ^(/downloader|/js|/404|/report)(.*) {
    include fastcgi_params;
    fastcgi_index index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$1/index.php$1;
    fastcgi_read_timeout 600;
    fastcgi_pass  127.0.0.1:9000;
  }
 
  location ~* \.php {
    include fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    fastcgi_read_timeout 600;
    fastcgi_pass  127.0.0.1:9000;
  }
 
}

This config works for version 1.7:
server {
  root    /home/magento/web/;
  index    index.php;
  server_name magento.example.com;
  location / {
    index index.html index.php;
    try_files $uri $uri/ @handler;
    expires 30d;
  }
  location ~ ^/(app|includes|lib|media/downloadable|pkginfo|report/config.xml|var)/ { internal; }
  location /var/export/ { internal; }
  location /. { return 404; }
  location @handler { rewrite / /index.php; }
  location ~* .php/ { rewrite ^(.*.php)/ $1 last; }
  location ~* .php$ {
    if (!-e $request_filename) { rewrite / /index.php last; }
    expires off;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param MAGE_RUN_CODE default;
    fastcgi_param MAGE_RUN_TYPE store;
    include fastcgi_params;
  }
}

Fooman Speedster is a popular extension that requires editing your server configuration. If you use it add this at the bottom of one of the server configurations above, right before the closing bracket.
 rewrite ^/minify/([0-9]+)(/.*.(js|css))$ /lib/minify/m.php?f=$2&d=$1 last;
 rewrite ^/skin/m/([0-9]+)(/.*.(js|css))$ /lib/minify/m.php?f=$2&d=$1 last;
 
 location /lib/minify/ {
   allow all;
 }