Writing custom nginx rules for an application
A general reference for routing requests correctly when an application has more than one entry point, such as Laravel, Symfony, or similar frameworks.
Every domain can carry its own extra nginx rules. Go to Service Configuration → nginx, select the domain from the list, and paste the rule into its custom rules box, then save. These rules are kept separately from the domain's main configuration, so they survive certificate renewals and any later rebuild of the domain's web server settings. Anything added here is checked against the live server before being applied - a rule that would stop nginx from starting is refused, with nothing changed, rather than applied.
This article covers one specific, common case: an application that has more than one independent section, each with its own entry file in its own subfolder, rather than a single index.php everything goes through. Most modern frameworks don't need this at all. It mainly applies to applications built with several separate modules - for example a sign-in section, an admin section, and a reporting section, each able to run on its own.
The problem this solves
An ordinary web server rule sends any address that isn't a real file to the application's one main entry file, which is exactly right when there's only one. For an application with several independent sections, that same rule sends every one of those sections to the wrong entry file, which usually shows up as the symptom covered in the "redirect loop" article in this section.
The rule
Replace the folder names below with the application's own section names - check its own documentation, or look for which top-level folders each contain their own index.php, rather than guessing.
location ~ ^/(admin|api|session)(?!.*\.php)(/|$) {
try_files $uri $uri/ /$1/index.php?$query_string;
}
This sends a request for anything under those folders - a page, not a real file - to that folder's own entry file instead of the site's main one. A request for a real file already on disk, including a static image or stylesheet sitting in the same folder, is served directly and never touches this rule at all.
(?!.*\.php) part matters more than it looks. Without it, this same rule also matches the very file it rewrites to - the request ends up being handed to this rule a second time, finds a real file sitting there, and serves it as a plain download instead of letting it run as PHP. Leaving this part out is the single most common mistake when writing a rule like this.Confirming it worked
- Visit one of the application's own section addresses directly - its sign-in page is usually the easiest to check. It should load normally rather than redirecting back to itself.
- Load an ordinary page on the application's main section too, to confirm nothing about its everyday behaviour changed.