Skip to main content

Working with Request Processing

1. Understanding Request Processing Phases

Phase Description Key Directives Notes
Initialization Initial setup of request context and variables. variables_hash_bucket_size Configures hash table size for variables.
URI Processing Processing of the URI including decoding and normalization. location, rewrite URI modification can happen here via rewrite rules.
Header Parsing Parsing of HTTP headers from the client request. limit_req, limit_conn Used for rate limiting and connection control.
Content Handling Processing of request body and content type handling. client_max_body_size, proxy_pass Controls how large a request body can be.
Filtering Applying filters to the request before passing it forward. gzip, map Can be used to compress or transform content.
Upstream Handling Forwarding the request to upstream servers. upstream, proxy_pass Used for load balancing and reverse proxying.

Example: Basic Request Flow Configuration

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

2. Using Post Read Phase

Directive Description Context Default
post_action Sets the action to be executed after the main request is processed. http, server, location none
post_action_if Conditionally sets the action to be executed after the main request is processed. http, server, location none

Example: post_action directive usage

location / {
    proxy_pass http://backend;
    post_action /log_request;
}

location /log_request {
    access_log off;
    return 204;
}

Example: post_action_if directive usage

location / {
    proxy_pass http://backend;
    post_action_if $status = 200 /log_success;
    post_action_if $status != 200 /log_error;
}

location /log_success {
    access_log off;
    return 204;
}

location /log_error {
    access_log off;
    return 500;
}

3. Using Server Rewrite Phase

Directive Description Usage
rewrite Performs a rewrite of the URI using a regular expression and replacement string. rewrite ^/old-path/(.*)$ /new-path/$1 permanent;
rewrite_log Enables logging of rewrite operations to the error log. rewrite_log on;
break Stops processing the current rewrite rules and continues with the next phase. if ($request_uri ~* ^/old-path/) { rewrite ^/old-path/(.*)$ /new-path/$1 break; }
last Stops processing the current rewrite rules and starts a new location block matching the rewritten URI. rewrite ^/old-path/(.*)$ /new-path/$1 last;
return Stops processing and returns a specific HTTP status code or URL. rewrite ^/old-path/(.*)$ /new-path/$1 return 301;

Example: Basic Rewrite Rule

location /old-path {
    rewrite ^/old-path/(.*)$ /new-path/$1 last;
}

Example: Rewrite with Permanent Redirect

rewrite ^/old-path/(.*)$ /new-path/$1 permanent;
Note: The last flag causes the rewrite to be processed in a new request cycle, while break stops further processing of rewrite rules in the current context.
Warning: Be cautious with permanent redirects as they can cause issues if not properly configured, potentially leading to redirect loops.

4. Using Find Config Phase

Directive Description Values Notes
find_config Enables or disables the find config phase on, off Default is off. When enabled, Nginx will process the find config phase before handling the request.
find_config_phase Specifies the phase in which find config is executed rewrite, access Can be set to rewrite or access phases.

Example: Enabling Find Config Phase

server {
    listen 80;
    server_name example.com;

    find_config on;
    find_config_phase rewrite;

    location / {
        return 200 "Find config phase enabled";
    }
}
Note: The find_config directive is used to control how Nginx processes configuration during the find config phase. It's particularly useful in complex configurations where you want to ensure specific phases are executed before the main request handling.

5. Using Rewrite Phase

Directive Description Example
rewrite Performs a rewrite on the URI rewrite ^/old-path/(.*)$ /new-path/$1 permanent;
rewrite_log Enables logging of rewrite operations rewrite_log on;
if Conditionally executes directives based on a condition
if ($request_uri ~* "^/api/v[0-9]+/") {
    rewrite ^/api/v[0-9]+/(.*)$ /api/$1 break;
}
Note: The rewrite directive is processed in the rewrite phase, which happens before the content phase.
Warning: Using rewrite with permanent or redirect can cause infinite loops if not handled carefully.

Rewrite Phase Workflow

  1. Match the request URI against configured patterns
  2. Apply rewrite rules in order of appearance
  3. Redirect or internally redirect based on flags

6. Using Post Rewrite Phase

Directive Description Context Default
post_action Defines a command to be executed after the main request is processed. http, server, location none
post_action_if Conditionally executes a post-action based on a variable or condition. http, server, location none

Example: Setting a Post-Action

location / {
    proxy_pass http://backend;
    post_action /log_request;
}

Example: Conditional Post-Action

location / {
    proxy_pass http://backend;
    post_action_if $status = 200 {
        return 301 /redirect;
    };
}
Note: The post_action directive runs after the main request is completed and can be used for logging or redirecting based on response status.

7. Using Preaccess Phase

Directive Description Values Notes
access_by Executes a script or module during the preaccess phase on, off Can be used to implement custom authentication or rate limiting logic
access_by_lua Executes Lua code in the preaccess phase lua_code Part of the Nginx Lua module (ngx_lua)
access_by_lua_file Executes Lua code from a file in the preaccess phase file_path Part of the Nginx Lua module (ngx_lua)

Example: Using access_by_lua to check a header

location / {
    access_by_lua '
        local auth_header = ngx.var.http_authorization
        if not auth_header then
            ngx.status = 401
            ngx.say("Authorization required")
            ngx.exit(401)
        end
    ';
    proxy_pass http://backend;
}

8. Using Access Phase

Directive Description Values Notes
access_by Executes a script or module during the access phase on, off Can be used for authentication or rate limiting
access_log Enables or disables logging of requests on, off Can be configured to log to a file or syslog
log_format Defines the format of log entries format_name, format Allows customizing the log output with variables

Example: Basic access_log configuration

access_log /var/log/nginx/access.log;

Example: Custom log format

log_format custom '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';

9. Using Post Access Phase

Directive Description Context Example
post_action Sets the action to be executed after the main request is processed. http, server, location post_action /log;
post_action_if Executes a post-action conditionally based on a variable. http, server, location post_action_if $status = 200 { post_action /log; }

Example: Setting a Post-Action

location / {
    proxy_pass http://backend;
    post_action /log;
}

Example: Conditional Post-Action

location / {
    proxy_pass http://backend;
    post_action_if $status = 200 {
        post_action /log;
    };
}

10. Using Content Phase

Directive Description Values Notes
location Defines how to handle requests to a specific URI /, = /, ~ /pattern Use = for exact match, ~ for regex
root Defines the root directory for content /var/www/html Used to set base path for static files
index Specifies default files to serve when directory is requested index.html index.htm Can include multiple files in order of preference
try_files Checks for files in order and serves the first one that exists $uri $uri/ /index.html Useful for serving static files or fallbacks

Example: Serving Static Files

server {
    listen 80;
    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

Example: Custom Error Page

server {
    listen 80;
    root /var/www/html;

    location / {
        try_files $uri $uri/ /custom_404.html;
    }
}

11. Using Log Phase

Directive Description Values Notes
log_format Defines a log format format_name format Used to define custom log formats for access logs
access_log Enables or disables access logging path format Can be set at http, server, or location level
error_log Enables or disables error logging path level Level can be debug, info, notice, warn, error, crit, alert, emerg

Example: Custom Log Format

log_format custom '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';

access_log /var/log/nginx/access.log custom;

Example: Error Log Level

error_log /var/log/nginx/error.log warn;
Note: The log_format directive is used to define custom log formats. These can then be applied using the access_log directive.
Warning: Logging to files can impact performance. Consider using a dedicated logging service or rotating logs to prevent disk space issues.

12. Understanding Phase Handlers

Phase Description Handlers Notes
rewrite Processes rewrite directives and modifies the URI rewrite, return Executed in the order defined in configuration
access Handles access control and authentication auth_basic, allow, deny Can block requests based on IP or credentials
content Generates the response content proxy_pass, fastcgi_pass, return Used for proxying or generating content directly
log Handles logging of request and response data access_log, error_log Logs are written here after content is generated

Example: Configuring Rewrite and Access Phase Handlers

server {
    listen 80;
    server_name example.com;

    # Rewrite phase handler
    rewrite ^/old-path/(.*)$ /new-path/$1 permanent;

    # Access phase handler
    location /admin {
        auth_basic "Admin Area";
        auth_basic_user_file /etc/nginx/htpasswd;
        allow 192.168.1.0/24;
        deny all;
    }

    # Content phase handler
    location / {
        proxy_pass http://backend;
    }
}

Was this article helpful?