Skip to content

Powered by Grav + Helios

Nginx

Nginx

Nginx is a HTTP server software with focus on core web server and proxy features. It is very common because of its resource efficiency and responsiveness under load. Nginx spawns worker processes, each of which can handle thousands of connections. Each of the connections handled by the worker get placed within an event loop where they exist with other connections. Within the loop, events get processed asynchronously, allowing work to be handled in a non-blocking manner. When the connection closes, it gets removed from the loop. This style of connection processing allows Nginx to scale incredibly far with limited resources.

Requirements

This page explains how to run Grav with Nginx as the HTTP server and PHP-FPM (FastCGI Process Manager) to process PHP scripts, so these packages need to be installed on your server:

  • nginx
  • php-fpm for PHP 8.3 or newer (Grav 2's minimum), for example php8.3-fpm on Ubuntu 24.04

Configuration

If you are new to Nginx and don't yet have a basic understanding of block directives/context, it is recommended to read the Nginx Beginners's Guide, especially the sections Configuration File’s Structure and Serving Static Content.

It is assumed that your Nginx configuration is located in /etc/nginx/ and your Grav installation is stored in /var/www/grav/. The structure of the configuration is a http block that contains general directives relevant for all pages served by Nginx, as well as one or multiple server blocks for each page, containing site-specific directives. The main server configuration file is nginx.conf and stores the http block, while site-specific configurations (server blocks) are stored in sites-available and symlinked to sites-enabled.

File Permissions

The /var/www directory and all contained files and folders should be owned by $USER:www-data (or whatever you name the Nginx user/group). The Permissions page explains how to set up file and directory permissions for Grav, in this case using a shared group. Basically what you want is 775 for directories and 664 for files in the Grav directory, so Grav is allowed to modify content and upgrade itself. You should add your user to the www-data group so you can access files that are created by Grav/Nginx.

A simpler alternative on a server that only hosts Grav is to run a dedicated PHP-FPM pool as your own user, so every file Grav writes is owned by you. The Ubuntu 24.04 VPS guide walks through that setup.

Example nginx.conf

The nginx.conf your distribution installs works with Grav as it is. The following is a tidied version of the default /etc/nginx/nginx.conf with a few improvements from github.com/h5bp/server-configs-nginx. See their repository for explanations of these settings, or the Nginx core module and http module documentation to look up specific directives.

nginx.conf:

NGINX
 1user www-data;
 2worker_processes auto;
 3worker_rlimit_nofile 8192; # should be bigger than worker_connections
 4pid /run/nginx.pid;
 5
 6events {
 7    worker_connections 8000;
 8    multi_accept on;
 9}
10
11http {
12    sendfile on;
13    tcp_nopush on;
14    tcp_nodelay on;
15
16    keepalive_timeout 30;
17    types_hash_max_size 2048;
18    server_tokens off;
19
20    # maximum file upload size
21    # update 'upload_max_filesize' & 'post_max_size' in /etc/php/8.3/fpm/php.ini accordingly
22    client_max_body_size 32m;
23    # client_body_timeout 60s; # increase for very long file uploads
24
25    # set default index file (can be overwritten for each site individually)
26    index index.html;
27
28    # load MIME types
29    include mime.types;
30    default_type application/octet-stream;
31
32    # logging
33    access_log /var/log/nginx/access.log;
34    error_log /var/log/nginx/error.log;
35
36    # turn on gzip compression
37    gzip on;
38    gzip_vary on;
39    gzip_proxied any;
40    gzip_comp_level 5;
41    gzip_min_length 256;
42    gzip_types
43        application/atom+xml
44        application/javascript
45        application/json
46        application/ld+json
47        application/manifest+json
48        application/rss+xml
49        application/xhtml+xml
50        application/xml
51        font/otf
52        font/ttf
53        image/svg+xml
54        image/x-icon
55        text/css
56        text/javascript
57        text/markdown
58        text/plain
59        text/xml;
60
61    # disable content type sniffing
62    add_header X-Content-Type-Options "nosniff" always;
63
64    # include virtual host configs
65    include /etc/nginx/conf.d/*.conf;
66    include /etc/nginx/sites-enabled/*;
67}

Note

Nginx only inherits add_header directives from an outer block when the inner block sets none of its own. The shipped Grav config adds a Cache-Control header for content-hashed bundles, so those responses do not carry headers set at the http level. If a header must be on every response, repeat it in that location block too.

Grav Site Configuration

Grav ships a configuration file for your site in the webserver-configs directory of every release. Copy it into your Nginx config directory:

BASH
cp /var/www/grav/webserver-configs/nginx.conf /etc/nginx/sites-available/grav-site

Open that file with an editor and:

  • replace server_name localhost; with your domain or IP (or leave it as localhost to run it locally)
  • replace root /home/USER/www/html; with root /var/www/grav;
  • uncomment listen 80;
  • check the fastcgi_pass line points at your PHP-FPM socket. The shipped unix:/var/run/php/php-fpm.sock is the version-independent link Debian and Ubuntu create; other systems may need the versioned socket (for example unix:/run/php/php8.3-fpm.sock) or a TCP address such as 127.0.0.1:9000

Then create a symbolic link of your site config in sites-enabled, check the configuration and reload Nginx:

BASH
ln -s /etc/nginx/sites-available/grav-site /etc/nginx/sites-enabled/grav-site
nginx -t
systemctl reload nginx

The shipped file has four sections, and the order matters:

  1. Index sends every request that is not a real file to index.php, so Grav can route it.
  2. Security refuses direct access to Grav's private folders (cache, logs, backup, user/config, user/accounts, user/data and so on) and to scripts and source files inside system, vendor and user, while still letting avatar images and public media uploads under user/data load. The config, accounts and data rules also match under an optional env/<name>/ prefix for multisite subsites.
  3. Static asset caching gives content-hashed bundles under _app/immutable/ (the Admin panel and other SvelteKit-based plugins and themes) a one-year immutable cache, and other static files a 30-day cache. It has to stay below the security rules: Nginx answers with the first regular-expression location that matches, so a caching rule placed above them would serve paths they are meant to refuse.
  4. PHP hands .php requests to PHP-FPM.

Important

Nginx does not read Grav's .htaccess, so upgrading Grav never updates your Nginx rules. After an upgrade, compare your site config with the release's webserver-configs/nginx.conf and copy any changed rules by hand.

Running Grav in a subfolder

To serve Grav from a subfolder such as https://example.com/grav/, change the index location to match it and point the fallback at the subfolder's index.php:

NGINX
location /grav {
    try_files $uri $uri/ /grav/index.php?$query_string;
}

The security rules are anchored at the site root (^/user/...), so prefix each of them with the subfolder as well (^/grav/user/...).

Fix against httpoxy vulnerability

httpoxy is a set of vulnerabilities that affect application code running in CGI, or CGI-like environments. (Source: httpoxy.org)

To protect your site, clear the Proxy header before it reaches PHP. Add this line inside the location ~ \.php$ block of your site config, after include fastcgi_params;:

NGINX
fastcgi_param HTTP_PROXY "";

Using HTTPS with Let's Encrypt

The quickest way to get a free certificate is Certbot, which obtains a Let's Encrypt certificate, adds the HTTPS server block to your site config and renews the certificate automatically:

BASH
apt install -y certbot python3-certbot-nginx
certbot --nginx -d example.com -d www.example.com

Using HTTPS with an existing certificate

To use a certificate you already have, create a file /etc/nginx/ssl.conf with the following content and adjust the paths to your certificate and key. The protocol and cipher settings follow Mozilla's intermediate configuration, which suits nearly every site. If your site and all its subdomains are HTTPS only, you can submit your domain for preloading in browsers at hstspreload.org; otherwise remove preload from the Strict-Transport-Security header.

ssl.conf:

NGINX
 1# set the paths to your certificate (full chain) and key files here
 2ssl_certificate /etc/ssl/certs/example.com.fullchain.pem;
 3ssl_certificate_key /etc/ssl/private/example.com.key;
 4
 5ssl_protocols TLSv1.2 TLSv1.3;
 6ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
 7ssl_prefer_server_ciphers off;
 8
 9ssl_session_cache shared:SSL:10m; # about 40000 sessions
10ssl_session_timeout 1d;
11ssl_session_tickets off;
12
13# submit domain for preloading in browsers at: https://hstspreload.org
14add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

Now change your Grav site config /etc/nginx/sites-available/grav-site so that plain HTTP requests redirect to HTTPS, served by a server block listening on port 443 that includes your ssl.conf (replace example.com with your domain). This example also redirects the www host to the bare domain:

grav-site:

NGINX
 1# redirect http to non-www https
 2server {
 3    listen [::]:80;
 4    listen 80;
 5    server_name example.com www.example.com;
 6
 7    return 301 https://example.com$request_uri;
 8}
 9
10# redirect www https to non-www https
11server {
12    listen [::]:443 ssl;
13    listen 443 ssl;
14    server_name www.example.com;
15
16    include ssl.conf;
17
18    return 301 https://example.com$request_uri;
19}
20
21# serve website
22server {
23    listen [::]:443 ssl;
24    listen 443 ssl;
25    # http2 on;  # nginx 1.25.1 and later; on older versions add `http2` to the listen lines instead
26    server_name example.com;
27
28    include ssl.conf;
29
30    root /var/www/grav;
31    index index.html index.php;
32
33    # ...
34    # the rest of this server block (the Index, Security, Static asset caching
35    # and PHP sections) is identical to the shipped webserver-configs/nginx.conf
36}

Finally check and reload your Nginx configuration:

BASH
nginx -t
systemctl reload nginx

Confirming it works

A request for a private file such as https://example.com/user/config/system.yaml should return 403 Forbidden, not the file's contents, while a media file you uploaded under user/data (for example a .jpg) should still load normally. The User Folder Exposure page explains the admin warning that fires when these rules are not being applied.