Setting Up an nginx / php-fpm Virtual Host for Magento 2
Dear Developer,
I understand your frustration with configuring the virtual host for Magento 2 using nginx and php-fpm. Don’t worry; I’ll guide you through setting it up correctly.
Understanding the Configuration
The provided configuration is a good starting point, but there are some adjustments to be made:
server {
listen 80;
server_name local.magento2.com;
root /home/www/magento2/;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location / {
index index.php;
try_files $uri $uri/ @handler; ## If missing pass the URI to Magento's front handler
expires off; ## Assume all files are cachable
}
location @handler { ## Magento uses a common front handler
rewrite ^/(.*)$ /index.php?$1 last;
}
# Foward php request to FastCGI server.
location ~ \.php$ {
fastcgi_pass php5-fpm-sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS off;
}
}
Fine-tuning the Configuration
Let’s enhance this setup:
-
Listen on port 443 for secure connections: Add
listen 443 ssl;. You’ll need to configure SSL/TLS later. -
Handle static content: Add the following location block to redirect requests for static content to Magento’s handler:
location /pub/static { rewrite ^/pub/static/(.*)$ /pub/static.php?resource=$1&_redirect=1 last; } -
Enable gzip compression: Add the
gzipdirective at the server level to improve performance. -
Handle 404 errors gracefully: Update the try_files directive to catch 404s:
location / { index index.php; try_files $uri $uri/ /index.php?$query_string; expires off; ## Assume all files are cachable }
Connecting to php-fpm
The fastcgi_pass directive points to a fastCGI server socket. Ensure the php5-fpm service is running and the socket exists at the specified location.
location ~ \.php$ {
fastcgi_pass unix:/run/php/php7-fpm.sock;
# ... (rest of the block)
}
Conclusion
Remember to restart or reload nginx after making changes:
sudo systemctl reload nginx
This configuration should provide a solid foundation for running Magento 2 with nginx and php-fpm. For more advanced configurations and optimizations, I recommend checking out our guide on high-performance Magento deployments.
If you have any further questions or need specific guidance for your project, please don’t hesitate to reach out.
Happy coding!