Serving HTML and PHP from Multiple Folders on Nginx Host

Abstract: Configure Nginx to serve static HTML and dynamic PHP from separate folders using distinct location blocks with alias directives.

Created: 2026-09-02 by
Configure Nginx to serve static HTML and dynamic PHP from multiple folders by defining separate location blocks within a single server block. Use specific root directives for each path and apply the fastcgi_pass handler only to the PHP directory. This approach ensures that static assets are served directly while PHP files are processed by the backend interpreter, maintaining high performance and clear separation of concerns.

Understanding the Server Block Structure

The core of this configuration lies in how Nginx routes requests based on the URI path. When you have multiple folders, such as /var/www/html for static content and /var/www/php-app for dynamic scripts, you must guide Nginx to treat them differently. The default behavior often assumes all content is either static or requires processing, which can lead to errors when mixing types in different directories. To solve this, you do not need separate server blocks for each folder unless they use different ports or domains. A single server block listening on port 80 or 443 can handle multiple locations. The key is precision in your location definitions. You must explicitly tell Nginx where to look for files and which internal processor to invoke for specific file extensions.

Configuring Static HTML Directories

For folders containing only HTML, CSS, JavaScript, and images, you want Nginx to serve these files directly without involving PHP-FPM. This reduces overhead and speeds up load times significantly. Start by defining the general root for your site, but be careful if your paths diverge. If your HTML files are in a subdirectory like /public, you can create a dedicated location block. For example:
server {
    listen 80;
    server_name example.com;

    # General fallback or default root
    root /var/www/html;
    index index.html;

    location /static-html/ {
        alias /var/www/static-content/;
        try_files $uri $uri/ =404;
    }
}
Using alias instead of root inside the location block is crucial here. It maps the URL path exactly to the filesystem path. If you used root, Nginx might append the location prefix to the root path, resulting in a 404 error because the file structure would not match. The try_files directive ensures that if a file does not exist, Nginx returns a proper 404 response rather than passing the request to a processor that doesn't need it.

Handling PHP Files in Separate Folders

When you have a folder dedicated to PHP applications, you must enable the FastCGI process. This allows Nginx to communicate with PHP-FPM. Suppose your PHP application resides in /var/www/php-app. You need a location block that targets this specific path and passes matching files to the PHP processor.
    location /php-app/ {
        alias /var/www/php-app/;
        
        # Pass PHP files to PHP-FPM
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $request_filename;
        }
    }
Notice the nested location block. The outer block sets the alias for the directory. The inner block, using a regex ~ \.php$, specifically catches any request ending in .php. Inside this inner block, we define how to talk to PHP-FPM. The fastcgi_param SCRIPT_FILENAME variable is critical; it must point to the actual file on disk. Because we used alias, $request_filename/var/www/php-app/. If you mix PHP and HTML in the same root directory, the logic changes slightly. You would typically keep the main root directive at the server level and use a regex location for PHP that applies globally, while letting other files fall through to the default static handling. However, keeping them in separate physical folders simplifies permissions and security management.

Security and Permissions Considerations

Running PHP and static files from different folders offers security benefits. You can restrict execution permissions more tightly. Ensure that the web server user (usually www-data) has read access to both directories. For the PHP folder, write permissions may be needed for uploads or cache directories, but never for the executable PHP scripts themselves. It is also wise to prevent direct access to sensitive files. In your PHP location block, you can deny access to hidden files or backup files:
        location ~* /\. {
            deny all;
        }
This small addition prevents users from accessing .htaccess equivalents or version control directories like .git that might reside within your public-facing folders.

Troubleshooting Common Issues

If you encounter 502 Bad Gateway errors, check if PHP-FPM is running and if the socket path in fastcgi_pass matches your system's configuration. On many systems, the socket is located at /run/php/php-fpm.sock, but it may vary depending on your PHP version and installation method. You can verify the correct path by checking your PHP-FPM pool configuration file. Another common issue is the "No input file specified" error. This usually means the SCRIPT_FILENAME parameter is incorrect. Double-check that your alias directive ends with a slash and that the regex in the location block correctly identifies the PHP files. If you recently changed your directory structure, ensure that Nginx has reloaded its configuration using sudo nginx -t followed by sudo systemctl reload nginx. For deeper insights into isolating PHP processes, consider reviewing guides on PHP-FPM security isolation. Understanding how Nginx proxies requests helps clarify why misconfigurations in one block affect the entire server. Additionally, if you are managing multiple environments, similar principles apply to Docker setups where proxying can sometimes lead to timeouts if not configured correctly.

Frequently Asked Questions

Can I use the same root directory for both HTML and PHP?

Yes, you can serve both from the same root by using a regex location block for PHP files. This method relies on the file extension to trigger the FastCGI pass, while other files are served statically via the default location. It is simpler to manage but offers less granular security isolation than separate folders.

Why did I get a 404 error after adding the alias directive?

A 404 error often occurs if the alias path does not end with a trailing slash or if the try_files directive does not account for the aliased path correctly. Always ensure the alias points to an existing directory and that the URI structure matches the filesystem layout exactly.

How do I test my Nginx configuration before reloading?

You should always run sudo nginx -t to syntax-check your configuration file. This command validates the directives and reports any errors in line numbers. Only proceed with systemctl reload nginx if the test returns success, preventing service downtime due to bad configurations.

What is the difference between root and alias directives?

The root directive appends the full URI to the specified path, while alias replaces the URI prefix with the specified path. Use root for standard sites and alias when mapping a URL path to a completely different directory structure, especially in nested location blocks.

Is it safe to run PHP-FPM and static files on the same server?

Yes, it is standard practice and highly efficient. Nginx handles static files natively, which is much faster than passing them through PHP. Running them together saves resources compared to separate servers, provided you configure permissions correctly to prevent unauthorized script execution.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More