SyliusのNginx構成

最近、eコマースプロジェクトの1つで、ますます人気が高まっているSyliusプラットフォームの使用を開始しました。 Syliusは、写真撮影Webサイトで使用した主要なPHPフレームワークであるSymfony2に基づいています。小規模なプロジェクトにはWooCommerceを使用していますが、Syliusはより現代的で強力なソリューションを提供しており、より野心的なeコマースWebサイトに間違いなく適していると考えています。

最初に苦労した問題は、SyliusをNginx + PHP-FPM + Ubuntu 14.04Webサーバーで正しく動作させることでした。標準のSymfony2構成ファイルといくつかの最適化から始めましたが、製品のサムネイルを機能させることができませんでした。 LiipImagineBundleを使用してオンザフライでサムネイルを生成していることが判明しました。これは、キャッシュの有効期限ルールセットに干渉していたため、表示しようとした画像サムネイルの404が発生しました。

静的ファイルの有効期限を1年先に設定するために誤って使用していたものは次のとおりです。

location ~ \.(js|css|png|jpeg|jpg|gif|ico|swf|flv|pdf|zip)$ {
    # Set expiry date to 1 year in the future.
    expires 365d;
}

これは通常問題なく機能しますが、実際の画像ファイルが存在するかどうかに関係なく、これらの拡張子のいずれかで終わるURLはapp.phpファイルを完全にバイパスすることも意味します。 Syliusのサムネイルは、URLリクエストに応じてオンザフライで作成されるため、サムネイルの作成が完全に中断されます。

修正は非常に簡単です。実際に存在する要求されたファイルの有効期限のみを設定します。それ以外の場合は、通常どおり、app.phpファイルに書き換えます。使用した最終的なNginx構成ファイルは次のとおりです。

server {
    server_name example.com;
    root /var/www/example.com/web;

    location / {
        try_files $uri @rewriteapp; # Redirect to app.php if the requested file does not exist.
    }

    # Development rule-set.
    # This rule should only be placed on your development environment.
    # In production, don't include this and don't deploy app_dev.php or config.php.
    location ~ ^/(app_dev|config)\.php(/|$) {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS off;
    }
    
    # Production rule-set.
    location ~ ^/app\.php(/|$) {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS off;
        
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/app.php/some-path
        # Remove the internal directive to allow URIs like this.
        internal;
    }

    # Static files rule-set.
    location ~ \.(js|css|png|jpeg|jpg|gif|ico|swf|flv|pdf|zip)$ {
        # Set rules only if the file actually exists.
        if (-f $request_filename) {
            # Set expiry date to 1 year in the future.
            expires 365d;

            # Further optimize by not logging access to these files.
            access_log off; 
        }

        # Rewrite to app.php if the requested file does not exist.
        try_files $uri @rewriteapp;
    }

    # Rewrite rule for PHP files.
    location @rewriteapp {
        rewrite ^(.*)$ /app.php/$1 last;
    }

    error_log /var/log/nginx/example.com_error.log;
    access_log /var/log/nginx/example.com_access.log;
}

それでおしまい。サムネイルはオンザフライで適切に生成されるようになりましたが、既存の画像も適切な有効期限ヘッダーを使用しています。これがうまくいったかどうか、または別のアプローチを使用したかどうかをお知らせください。ハッピーコーディング!