Setting up nginx with Contao 4
by Thomas Urban
Running web sites based on Contao with nginx has always been some sort of messy. However, Contao 4.x makes things a lot easier today. Here comes the configuration file that's highly similar to the one used with our hosting service.
server {
listen 80;
server_name www.foo.com;
root /var/www/www.foo.com/web;
#
# Rewrite all requests for non-exposed files to /web/app.php.
#
location / {
index app.php index.html;
try_files $uri $uri/ /app.php/$uri?$args;
}
#
# Create separate location for Contao backend to increase POST request size
# there.
#
# NOTE! This location is circumventing regular request "rewriting" using
# try_files and thus needs to patch SCRIPT_FILENAME and SCRIPT_NAME
# of fastcgi_params to mock the regular behaviour of PHP processing.
#
location ~ ^/contao(/|$) {
include fastcgi_params;
fastcgi_pass unix:/run/php/php7.1-fpm.sock;
fastcgi_index app.php;
fastcgi_param PHP_ADMIN_VALUE "open_basedir=/var/www/www.foo.com/:/tmp/";
# mock information on script to be processed in PHP actually
fastcgi_param SCRIPT_FILENAME $document_root/app.php;
fastcgi_param SCRIPT_NAME /app.php;
client_max_body_size 20m;
}
#
# Pass all requests for PHP documents to PHP FPM service.
#
location ~ \.php(/|$) {
include fastcgi_params;
fastcgi_pass unix:/run/php/php7.1-fpm.sock;
fastcgi_index app.php;
fastcgi_param PHP_ADMIN_VALUE "open_basedir=/var/www/www.foo.com/:/tmp/";
}
#
# Declare images to be cached for up to 30 days.
#
location ~* \.(gif|jpg|png)$ {
expires 30d;
}
}
There is something special about this example: A separate section matching location ~ ^/contao(/|$)
has been added to handle all requests in subfolder /contao w/o routing requests the common way used for all frontend requests. Thus it's copying rules forwarding requests to PHP-FPM, but also faking some FastCGI parameters required due to skipping the try_files part. All this is used to enable additional customizations of nginx configuration applying in Contao backend, only. In this case it is an increased limit for POSTing requests e.g. for uploading larger files.