Serve HTML/JSON Exact Path Exact URL on Tech Support Site

Abstract: Configure Nginx or Apache to serve HTML and JSON files at exact paths without fallback logic, preventing content type mismatches.

Created: 2026-09-25 by
To serve HTML and JSON files with exact paths on a tech support site, you must configure your web server to map specific URLs directly to their corresponding file locations without fallback logic or generic routing. This approach ensures that API endpoints return pure JSON data while documentation pages serve static HTML, improving both user experience and application reliability by preventing unintended content type mismatches or redirect loops.

Understanding Exact Path Routing

Exact path routing means that a URL like /api/status serves only the JSON file located at /var/www/html/api/status.json, and /docs/intro serves only the HTML file at /var/www/html/docs/intro.html. Unlike Single Page Applications (SPAs) that rely on a catch-all rule to route all traffic to index.html, this method requires explicit configuration for each resource. This is particularly useful for tech support sites where distinct API responses and static help articles coexist on the same domain. When implementing this, you avoid the common pitfall of serving an HTML page when a JSON response is expected, which can break JavaScript consumers. It also prevents the browser from caching dynamic API data as static HTML. The core principle is precision: every defined URL maps to exactly one physical file or directory index, with no ambiguity.

Configuring Nginx for Exact Paths

Nginx provides robust tools for mapping URIs to file system paths. To serve JSON and HTML correctly, you must ensure MIME types are handled appropriately so the browser interprets the content correctly. First, verify that your mime.types file is included in your main configuration. This ensures that .json files are served with the correct application/json header. Without this, browsers may treat JSON as plain text, causing parsing errors in client-side scripts. Next, define your server block with specific location blocks. Avoid using a generic location / { try_files $uri $uri/ /index.html; } rule, as this will intercept all requests and potentially serve HTML for JSON endpoints. Instead, use precise matches.
server {
    listen 80;
    server_name example.com;
    root /var/www/html;

    # Serve HTML files
    location /docs/ {
        try_files $uri $uri/ =404;
    }

    # Serve JSON files
    location /api/ {
        default_type application/json;
        try_files $uri =404;
    }

    # Fallback for other assets
    location /assets/ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
In this configuration, /docs/intro.html is served via the first location block. The try_files directive checks if the file exists; if not, it returns a 404 error rather than falling back to an index file. For the API, the default_type directive forces the JSON MIME type, ensuring consistency even if the file extension is missing or ambiguous.

Configuring Apache for Exact Paths

Apache uses .htaccess files or virtual host configurations to achieve similar results. The key is to disable directory indexing and prevent automatic fallbacks. Use the FilesMatch directive to handle JSON files specifically. This allows you to set headers and MIME types for specific file extensions.
# .htaccess in /var/www/html

# Disable directory browsing
Options -Indexes

# Handle JSON files

    Header set Content-Type "application/json"
    # Ensure no HTML fallback
    RewriteEngine Off


# Handle HTML files explicitly if needed
RewriteRule ^docs/(.*)$ docs/$1.html [L]
The Header set Content-Type command ensures that any file ending in .json is delivered with the correct MIME type. By turning off RewriteEngine within this block, you prevent any global rewrite rules from interfering with the direct file access. This is crucial for maintaining the integrity of API responses. For HTML files, you can rely on Apache's default behavior of serving index.html in directories, or use RewriteRule to map clean URLs to specific HTML files. However, be cautious not to create circular redirects. Always test your configuration with apachectl configtest before reloading the service.

Testing and Validation

After configuring your server, validate the setup using command-line tools. Use curl to check the response headers and body.
curl -I http://example.com/api/status
curl -I http://example.com/docs/intro
The first command should return a 200 OK status with Content-Type: application/json. The second should return Content-Type: text/html. If you see text/plain for JSON, revisit your MIME type configuration. If you see HTML for the API endpoint, check for overriding rewrite rules or incorrect location blocks. Additionally, inspect the network tab in your browser's developer tools. Navigate to your tech support site and trigger an API call. Verify that the response payload is valid JSON and not an HTML error page. This visual confirmation helps identify issues that automated tests might miss, such as server-side rendering errors that leak into API responses. For related troubleshooting, you might encounter issues with symlinks ignoring CSS files. See HTML File Opened via Symlink Ignores CSS: A Tech Support Reminder for details on resolving asset loading problems. Also, if you are fetching these JSON resources via PHP, refer to Retrieving JSON with Curl in PHP to ensure proper client-side handling.

Frequently Asked Questions

Why does my JSON endpoint return HTML?

This usually happens because a generic fallback rule, like try_files $uri $uri/ /index.html;, catches the request when the file is not found or due to misconfigured MIME types. Ensure your location blocks are specific and do not share fallback logic with your HTML routes.

Can I use a single location block for both HTML and JSON?

Yes, but you must differentiate them based on file extension or URI path. Using try_files with different default types for each extension can work, but separate location blocks provide clearer control over headers and security policies for each content type.

How do I handle query parameters in exact path routing?

Exact path routing typically ignores query parameters for file lookup. If your API relies on query strings (e.g., /api/data?user=123), you cannot serve a static file directly. You must use a backend script (like PHP or Node.js) to process the request and generate the JSON response dynamically.

What if I need to serve both HTML and JSON from the same directory?

You can mix them in the same directory, but you must ensure the web server distinguishes them by extension. Configure default_type or MIME mappings to recognize .html as text and .json as application/json. Avoid renaming files to bypass extension checks, as this breaks MIME detection.

Is it safe to disable directory indexing for API folders?

Yes, it is highly recommended. Disabling directory indexing (Options -Indexes) prevents users from browsing the raw file structure of your API, which could expose sensitive filenames or internal organization. Always pair this with strict access controls and validation in your backend logic.

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