Skip to content
The Chat Archive
gpt-4o-2024-05-13· OpenAI WildChat-4.8M (AI2)

what is nginx regular expression tilda means in location

  1. User

    what is nginx regular expression tilda means in location

  2. Assistant

    In NGINX, the ~ (tilde) in the location directive indicates that the following pattern is a case-sensitive regular expression. There is also ~* which indicates a case-insensitive regular expression.

    Here are a few examples to illustrate the usage:

    1. Case-sensitive regular expression (~):
    location ~ \.php$ {
        # This block will match URLs ending with ".php"
        # Example: /index.php, /test.php
        # It will not match: /index.PHP
    }
    
    1. Case-insensitive regular expression (~*):
    location ~* \.php$ {
        # This block will match URLs ending with ".php" regardless of case
        # Example: /index.php, /test.php, /index.PHP, /TEST.PHP
    }
    

    Additional Notes

    • Regular expressions in NGINX are evaluated in the order they are defined within a configuration block.
    • NGINX also provides other types of location modifiers:
      • / - Exact match. This is very rare as it cannot be used together with regex modifiers.
      • = - Exact match for the complete request.
      • ^~ - If this location is matched, it is used immediately and the search terminates. This is useful for prefix-based matching.

    Example with Combined Directives

    server {
        ...
    
        # Static file serving (priority over PHP regex matches)
        location ^~ /static/ {
            # Serve static files
        }
    
        # Case-sensitive regex to match PHP files
        location ~ \.php$ {
            # Handle PHP requests
        }
    
        # Case-insensitive regex to match images
        location ~* \.(jpg|jpeg|png|gif|ico)$ {
            # Handle image requests
        }
    
        ...
    }
    

    In this example:

    • Requests starting with /static/ will be served by the static file handler due to ^~.
    • Requests ending with .php will match the case-sensitive regex.
    • Image file extensions will match the case-insensitive regex (~*).

    Understanding these location modifiers and how they interact can help with efficiently routing and handling different types of requests in an NGINX configuration.