Serving Moodle files with X-Sendfile and X-Accel-Redirect

Moodle can hand file downloads to Nginx or Apache so PHP workers stop streaming large files. This page covers the xsendfile settings, the aliases to configure, the trade-offs and what to confirm before rollout.

On this page

Why Moodle file serving with X-Sendfile matters for a busy site

Your Moodle site spends part of every busy hour with PHP workers streaming course files to students, and those workers are the same processes that render pages, run quiz attempts and answer web service calls. The xsendfile setting in config.php lets Moodle hand the file transfer to the web server instead. Moodle's config-dist.php lists three header modes: X-Sendfile for Apache, X-LIGHTTPD-send-file for Lighttpd and X-Accel-Redirect for Nginx. In each case PHP checks permissions, sends a header naming the file path, and exits, while the web server reads and transmits the file. The xsendfilealiases setting covers directories that sit outside the default data location, such as custom dataroot, cache or temp paths that the web server must be allowed to read.

This is a file-serving change, not a general scaling fix. It helps most when a site has many large downloads, such as lecture videos, PDFs or SCORM packages, served alongside heavy page traffic, because each file no longer ties up a PHP worker for the length of the transfer. It does little for slow database queries, session lock contention or cache misses, which need their own work. Before enabling it, confirm the header mode matches your web server build, that the web server user can read every directory listed in the aliases, and that the file paths Moodle emits resolve correctly behind any proxy in front of the site. Test one download of each file type you serve, because a misconfigured alias fails at the moment a learner clicks a link.

The decision is therefore whether your bottleneck is file delivery. Look at PHP worker utilization during peak file downloads and compare it with the same window during quizzes or logins. If workers are busy with transfers, X-Sendfile removes that load and frees capacity for interactive requests. If they are busy elsewhere, profile the site first, because this change will not move that bottleneck. Ask your infrastructure team which header your web server supports and who owns the alias configuration when the storage layout changes.

Which header Moodle sends for each web server

Moodle does not serve files itself when X-Sendfile is enabled. It sends a small header that tells the web server in front of it which file to return, so the header Moodle sends must match the server that receives it. The three cards below cover the supported headers and the configuration each one depends on.

Apache uses X-Sendfile

When the web server is Apache, set xsendfile to X-Sendfile in config.php. Apache then needs the mod_xsendfile module loaded and the XSendFile On directive enabled in the relevant virtual host or directory. Without that module, Apache ignores the header and the file request may fail or be served by PHP. Check the configuration with a file download from a course before you rely on it in production.

Moodle config-dist.php

Nginx uses X-Accel-Redirect

When the web server is Nginx, set xsendfile to X-Accel-Redirect. Nginx does not read a file path from the header directly. It needs an internal location that maps to the Moodle data directory, and Moodle's xsendfilealiases setting must translate each physical path into that location. A mismatch between the alias and the Nginx location is the most common reason downloads return errors.

Lighttpd uses X-LIGHTTPD-send-file

When the web server is Lighttpd, set xsendfile to X-LIGHTTPD-send-file. Lighttpd reads this header and serves the named file, so the file path must be reachable by the Lighttpd process user. Confirm the header name against the Moodle version you run, since the setting is documented in config-dist.php and changes should be tested on a staging copy.

Honour the header the setting names

The header Moodle sends and the header the web server acts on must be identical. If xsendfile names one header but the proxy in front of Moodle strips it, rewrites it or ignores it, users receive the page body instead of the file. Test both a small PDF and a large resource, and check the response headers in the browser developer tools to confirm the file arrives from the web server.

Follow the server in front of Moodle

The header choice follows the web server that receives traffic from PHP, not the operating system or the database. In a layered design with a load balancer, the header must be understood by the node that actually returns the file. Ask your platform team to name the server at each hop, and record the chosen header in your configuration standards so later upgrades and host rebuilds keep the same setting.

Configuration options and when each fits

This table compares the xsendfile values and the xsendfilealiases setting in config.php, with the directories each one usually covers. Read each row as a choice you make for your web server, then check the consequence column before you change anything in production.

OptionWhat it setsWhen it fitsWhat breaks if it is wrong
xsendfile set to X-Accel-RedirectMoodle sends an internal redirect header that Nginx reads and serves from diskYour web tier is Nginx and you want PHP workers to hand off file deliveryNginx has no matching internal location, so downloads fail or return errors
xsendfile set to X-SendfileMoodle sends a header that Apache's mod_xsendfile reads and serves from diskYour web tier is Apache with the module installed and enabledWithout the module, the header is ignored and PHP streams the file itself, removing no load
xsendfile set to X-LIGHTTPD-send-fileMoodle sends the Lighttpd variant of the same headerYour web tier is Lighttpd and you have confirmed the directive is activeMismatched headers mean no offload, so the load you expected stays on PHP workers
xsendfile left unset or disabledMoodle streams every file through PHPSmall sites, test builds, or stacks where no supported web server handles the headerLarge downloads and media tie up PHP workers for the full transfer time
xsendfilealiasesMaps a Moodle directory to a path the web server can serve, such as dataroot, cache or temp locationsDirectories live outside the default dataroot path or on a separate mountA missing alias means the web server cannot find the file, so the request fails or falls back to PHP
Dataroot directoryStores uploaded course files, backups and user filesUsually the main target for offload because it holds the largest filesPermissions or a missing alias expose the wrong path or block downloads for students
Cache and temp directoriesHold cached data and temporary files that some downloads pass throughAdd an alias only where a file is actually served from that directoryServing cache paths you do not intend to expose can leak internal data
Web server internal locationThe Nginx or Apache location block that matches the alias pathMust match each alias exactly, including trailing slashesA path mismatch returns 404 or directory errors, and the fault is often silent until users report it

Setting up X-Accel-Redirect on Nginx step by step

This sequence takes a Moodle site from a PHP-served file path to an Nginx-served one, with each step closed by a check so a failure is caught before it reaches users. The order matters because Moodle only sends the internal redirect after the Nginx locations exist and the document root is correct.

  1. Confirm the Moodle and Nginx versions

    Record the Moodle version from the site administration page, the PHP version from the command line, and the Nginx version with nginx -v. Check that the Moodle version is one whose stated requirements your PHP and database already meet, because a version mismatch can surface later as a misleading file error. Confirm the exact Nginx build and PHP-FPM socket path with your own environment, since these values differ between distributions. Done when you have written these values down and the site loads cleanly from the front page.

  2. Point the document root at public

    On Moodle 5.1 or later, set the Nginx root directive to the new /public directory inside the Moodle code folder rather than the main Moodle folder. Pointing at the main folder can expose directory listings or cause errors, so this change comes before any file-serving work. Reload Nginx, then load the front page and a course page. Done when both pages load without errors and a request for a directory path returns a not-found response instead of a listing.

  3. Create a dataroot directory with restricted access

    Confirm that the dataroot directory is outside the web root, owned by the account that runs PHP-FPM, and not readable by other local users. Check that the path in config.php matches the directory on disk. This keeps the file store unreachable by URL, so the only route to a file is the one you define in the next steps. Done when a direct request for a path inside dataroot returns a not-found or forbidden response from Nginx.

  4. Define internal locations for each alias

    Add an internal location block in the Nginx server configuration for each directory you will serve through X-Accel-Redirect, typically the dataroot path and any cache or temporary directories you alias. Mark each location with the internal directive so clients cannot request it directly, and set the alias to the matching directory on disk with a trailing slash. Test the configuration with nginx -t and reload. Done when nginx -t reports the configuration is successful and a direct request to an internal path returns a not-found response.

  5. Set xsendfile and xsendfilealiases in config.php

    In config.php, set xsendfile to X-Accel-Redirect because your server is Nginx. Then add an xsendfilealiases entry for each directory, mapping the real path on disk to the internal location name from the previous step, so the header Moodle sends matches what Nginx expects. Use the config-dist.php reference to confirm the exact key format for your Moodle version. Purge the Moodle caches from the administration page so the change takes effect. Done when the configuration file parses without errors and the site still loads.

  6. Test downloads and permissions

    Log in as a student and as a teacher, then download a file from a course resource, an assignment submission you are allowed to see, and an uploaded image. Repeat with a user who lacks access to the same file and confirm the download is refused. Check that the response carries the file with the expected content type and size. Done when authorized downloads succeed for each role and unauthorized attempts fail, because Moodle still makes the access decision before Nginx sends anything.

  7. Confirm PHP no longer serves the file

    Watch the PHP-FPM slow or access log and the Nginx access log while downloading a large file. The Moodle request should return quickly with the internal redirect, and Nginx should record the file transfer. If PHP still streams the bytes, check that the xsendfile setting is applied, the alias path matches the real path exactly, and the Moodle caches were purged. Done when the file transfer appears under Nginx and PHP workers do not stay occupied for the length of the download.

How the PHP handoff and the web server response fit together

Moodle keeps the decision about who may read a file, and the web server only does the byte transfer. When a user requests a file, Moodle's PHP code runs the usual checks: the user is signed in, the file belongs to a context the user can see, and any capability or role rules pass. Only then does Moodle send an empty response body with a header that names the file's path on disk. With the xsendfile setting in config.php set to X-Accel-Redirect for Nginx or X-Sendfile for Apache, the web server reads that header, opens the file, and streams it to the browser. The PHP worker is released as soon as the header is sent.

The security model depends on one rule: the internal path must not be reachable by a direct request. If Nginx or Apache exposes the dataroot location to clients, anyone who knows or guesses a file path can download it without passing Moodle's checks. The internal location should be defined as an internal-only location in Nginx, or the equivalent restriction in Apache, so that only the header-driven redirect can reach it. Confirm this with a direct request to the internal path from outside the server, which should be refused, and then confirm that a file download through Moodle still works for a user with access and fails for one without.

Before enabling the handoff, decide which paths will be served this way and check that the web server user can read them. The xsendfilealiases setting maps Moodle directories that sit outside the default dataroot to matching internal locations, so a mismatch between the alias and the server block results in failed downloads rather than an access error. Check the current Moodle configuration reference in the Moodle config-dist.php file for the exact key names and option formats for your Moodle version, and test each file type, including large uploads, backups and course files, after the change.

Request flow for a file download with X-Accel-Redirect

The request starts at the browser and reaches the web server on the public side. Moodle runs in PHP on the internal side, checks the user's permission to the file, and returns an X-Accel-Redirect header instead of the file bytes. The web server then reads the file from an internal location that clients cannot address directly and sends it to the user. Check that the internal location is not reachable from outside and that the header path matches the alias configured in Moodle.

Moodle authorizes the request, while Nginx streams the file from an internal location.

Security risks when the web server serves Moodle data

Handing file delivery to Nginx or Apache moves an access decision out of PHP and into web server configuration. The cards below cover the exposure paths that open up when that split is wrong, and the operational checks that keep it from drifting after go-live.

Dataroot exposed to direct requests

The dataroot directory holds uploaded files, backups and temporary data, and it must never be reachable by URL. If the web server document root or an alias maps onto it, anyone who guesses a path can fetch files that Moodle would only release after a capability check. Confirm that no location block or alias points at dataroot, and test that a direct request to a known path returns a denial rather than file content.

Misconfigured aliases serving outside intended paths

Each entry in xsendfilealiases tells Moodle which internal path the web server may serve, so a broad or mistyped alias can expose more of the filesystem than intended. A prefix that is too short, or a trailing slash that is missing, can match sibling directories. Review every alias against the exact directories listed in the Moodle configuration, and keep the list as short as the deployment needs.

Permission checks bypassed by internal redirects

With X-Sendfile or X-Accel-Redirect, PHP still runs the access check and then hands the web server a header naming the file. If a web server location is also reachable directly, a user can skip PHP and the capability check entirely. Confirm that the internal location only responds to headers set by PHP, and that the same file cannot be requested through a public path.

Path traversal and file ownership

Moodle builds file paths from stored records, but a misconfigured proxy, unexpected symbolic link or writable directory can let a crafted name point outside the intended tree. Run the web server as an account that can read Moodle files but cannot write to code or dataroot where it does not need to. Check ownership and permissions on dataroot after each restore, because a restore run as root can leave files the web server cannot read or that are writable by other users.

Access logs for internal file delivery

Requests that PHP authorizes and the web server then serves can look identical in access logs, so incident responders may not see which user received which file. Log the request path, status, response size and the upstream response where possible, and keep these logs with the Moodle event log. Ask the team who reviews them and how long they are kept.

Testing unauthenticated requests and patch cadence

Repeat the direct-request tests after every web server change, Moodle upgrade and certificate or proxy update, since configuration drift is common. Include anonymous requests to file URLs, requests for dataroot, cachedir and tempdir paths, and traversal attempts. Follow Moodle's security releases and the web server's own advisories, and agree in writing who applies them and how quickly.

Moodle config-dist.php

Questions buyers ask about X-Sendfile and X-Accel-Redirect

How much effort does switching Moodle to X-Sendfile take?

The configuration change itself is small: a few lines in config.php plus a matching block in the web server. The effort comes from everything around it: how many web nodes serve Moodle, where dataroot, cache and temp directories live, whether storage is shared across nodes, and how many file types and access paths must be checked. A single server with local storage is a short job. A cluster with NFS or object-backed storage, where each node must resolve the same paths, takes longer because each node needs its own verification. Ask any partner to break the quote into configuration, per-node work, storage review and testing.

What drives the cost of this change up or down?

The main drivers are the number of web servers, the number of distinct storage paths that need aliases, the web server in use, and how much testing the change needs before it reaches production. Costs are one-time for the design, configuration and test pass, and recurring only if the environment changes and the mapping must be revisited, for example after a storage migration or a Moodle upgrade. Ask the quote to state which paths are covered, which servers are in scope, and whether a rollback step is included.

Can our own team make this change without outside help?

Yes, if your engineers are comfortable editing the Moodle configuration file and the Nginx or Apache configuration, and can test file downloads with different user roles. The risk is not the syntax but the access checks: a misplaced alias can expose a file path that Moodle would normally gate through PHP. Teams that do it alone should still test restricted files, such as course files a student should not reach, from a non-enrolled account. An outside partner adds value mainly through the review of paths and the test plan, not the edit itself.

What do you need from us before work starts?

Plan to provide read access to the Moodle config.php and the web server configuration on every node, the actual paths for dataroot, cache and temp directories, and a description of how storage is mounted. You will also need test accounts with different roles, such as a student, a teacher and an unenrolled user, plus a staging copy of the site where changes can be tried first. Confirm with your platform team who can approve a change window, since the work affects how files are delivered to every user.

How long does testing take for this change?

Testing time depends on scope rather than on a fixed figure. A single-node site with a short list of file paths can be checked in a short session. A multi-node cluster needs each node tested, each file path class tested for access, and a check that downloads still work after a web server reload. Ask the partner to state the test matrix in the quote, including which roles, file types and nodes are covered, and how long a staging soak period will run before production.

Does X-Sendfile remove load from PHP workers, and how much?

It removes the byte-streaming work from PHP for files Moodle chooses to hand off. PHP still runs the access check, then returns a header telling the web server which file to send, so the worker is freed sooner. The amount of relief depends on how many file requests your site handles, how large the files are, and how many PHP workers you run. Measure before and after with your own profiling data rather than relying on a general figure.

What breaks when the setting is wrong?

The most common failures are files that return a 404 or a blank response because the alias does not match the real path, and files that download without the expected access check because a directory is exposed directly. Both appear in testing if the test plan includes restricted content and a range of file types. Moodle's own documentation on configuration explains the supported settings, and your partner should confirm the exact keys against the Moodle version you run before relying on them.

How DeployOpen scopes and delivers Moodle file serving

DeployOpen plans and delivers the web server side of Moodle file serving inside infrastructure you control, from the xsendfile setting and directory aliases to testing and handover. The work starts with your existing Nginx or Apache setup, your storage layout and the Moodle version you run, so the change fits your environment rather than a generic template.

How we scope

  • Review your current web server, PHP-FPM setup, dataroot location and Moodle version before agreeing any change.
  • Confirm which file types, course sizes and user groups the change must cover, and which paths must stay private.
  • Agree the written scope, deliverables and timeline before work starts, since most engagements are fixed-scope.

How we build

  • Configure the xsendfile setting in config.php for your web server, Apache, Nginx or Lighttpd, in a staged environment first.
  • Map xsendfilealiases for dataroot, cache and temp directories so the web server can reach them without exposing them publicly.
  • Test permissions, access control for private course files and the behavior of downloads, previews and range requests before go-live.

How we hand over

  • Document each web server rule, alias and Moodle setting with the reason it exists and the files it covers.
  • Provide a verification checklist your team can rerun after Moodle upgrades, web server changes or storage moves.
  • Walk through the rollback steps so your operations team can return to direct PHP file serving if needed.

How we support

  • Review the file serving configuration again when you move to a new Moodle release or change the document root layout.
  • Retest access rules after web server or certificate changes, as part of an ongoing retainer if you choose one.
  • Confirm with your team which Moodle and web server versions you run, since configuration names and behavior can change between releases.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.