How To Use Try_Files In Nginx To Serve Static Files And Proxy The Rest?

Published September 19, 2024

Problem: Serving Static Files and Proxying in Nginx

Nginx servers often need to handle static files and dynamic content. The challenge is to route requests to serve static files directly while proxying other requests to application servers. This setup needs a careful configuration to improve performance and resource usage.

The Solution: Using Try_Files Directive

Implementing Try_Files in Nginx

The try_files directive in Nginx helps serve static files and proxy dynamic content. This directive checks for files or directories in a set order and processes the request based on the first match.

Try_files attempts to serve files from the specified locations. If a file is not found, it moves to the next option in the list. This continues until a match is found or the final fallback option is reached.

The try_files directive offers benefits over using if statements and regular expressions:

  1. It simplifies the configuration by removing the need for multiple if statements.

  2. It is more efficient than using if statements and regular expressions, as it avoids extra checks.

  3. The configuration becomes easier to read and maintain with a clear structure.

  4. You can easily add or remove file types without changing complex regular expressions.

  5. It can handle various scenarios, including serving custom error pages if no matches are found.

By using try_files, you can create an efficient Nginx configuration for handling static files and dynamic content.

Example: Basic Try_Files Configuration

server {
    listen 80;
    server_name example.com;
    root /var/www/example.com;

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

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

This example shows a basic Nginx configuration using try_files. It first attempts to serve the requested URI directly, then checks if it's a directory, and finally falls back to processing through index.php if neither is found.

Nginx Configuration for Static and Dynamic Content

Setting Up the Location Block

To set up Nginx for handling static files and dynamic content, configure the main location block:

  1. Set the root directory for your static files.

  2. Use the try_files directive to check for static files before proxying to the backend server.

  3. Add cache control headers and disable access logging for static files to improve performance.

Example of a location block configuration:

location / {
    root /path/to/your/static/files;
    try_files $uri $uri/ @apachesite;

    expires 30d;
    access_log off;
}

In this setup, Nginx looks for the requested file in the root directory. If found, it's served directly. If not, the request goes to the named location @apachesite.

Tip: Optimize Static File Serving

Consider adding the sendfile on; directive to your Nginx configuration to improve the performance of static file serving. This directive enables the use of the sendfile system call, which allows Nginx to serve static files directly from the kernel space, reducing CPU usage and improving overall performance.

Creating a Named Location for Apache Proxy

For requests that can't be served as static files, set up a named location to proxy requests to your Apache backend:

  1. Set the headers for communication between Nginx and Apache.

  2. Specify the address and port of your Apache server.

Example of a named location block for proxying to Apache:

location @apachesite {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

This setup sets the proxy headers and passes the request to the Apache server on localhost at port 8080.

By combining these two location blocks, you create a setup where Nginx handles static files and proxies dynamic content to Apache.