A Detailed Guide to NGINX Location Directive + [Best Practices For NGINX Location Directive]

Try this guide with our instant dedicated server for as low as 40 Euros

Nginx Location

One of the reasons NGINX is a popular choice as a web server is the idea of the NGINX location directive. The location directive in the NGINX server block allows requests to be routed to the right place in the file system.

The directive tells NGINX to look for a resource by including files and directories and matching a location block to a URL.

In this article, we’ll explore the idea of the NGINX location directive and how to use it to solve common problems in website content management and delivery.

Let’s first discuss the prerequisites of working with the NGINX location directive and then dive into the details of using this directive.

Table of content

Prerequisites

  • A server machine with NGINX installed and active.
  • A non-root user with sudo privileges.

What is the NGINX Location Directive?

The NGINX location directive specifies separate configuration blocks for various URLs or URIs. This means you can configure NGINX to treat requests differently depending on the URL or URI being requested.

The two uses of the NGINX location directive are:

  • Specifying a location block that corresponds to a particular URL or URI
  • Specify a regular expression that matches several URLs or URIs.

The location directive is used in the NGINX configuration file’s server block. As an example, consider the following:

server {

    listen       80;

    server_name  example.com;

    location / {

        root   /var/www/html;

        index  index.html index.htm;

    }

    location /redswitches/ {

        root   /var/www;

        index  index.html index.htm;

    }

    location ~ \.php$ {

        root           /var/www/html;

        fastcgi_pass   127.0.0.1:9000;

        fastcgi_index  index.php;

        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;

        include        fastcgi_params;

    }

}

In the above example, we’ve defined three location blocks.

The first location block matches every URL or URI that begins with a forward slash (/), which includes every URL or URI that will be queried.

The second location block applies to any URL or URI that begins with /redswitches/.

The third location block accepts any URL or URI ending in .php.

Now, let’s dig a bit deeper into the directive’s syntax so that you can write your own NGINX location directive blocks.

Exploring the Syntax of NGINX Location Directive

The NGINX location block is placed in a server block or nested into another location block (with some restrictions).

The syntax for creating a location block is as follows:

Syntax of NGINX Location Directive

The location block’s modifier is optional. NGINX might process a URL differently when a modifier is included in the location block.

Some of the most common modifiers are as follows:

  • None: If no modifiers exist in a location block, the requested URI is matched against the beginning of the requested URI.
  • =: The equal sign matches a location block to a URI.
  • ~: The tilde symbol is used for matching a case-sensitive regular expression against a requested URI.
  • ~*: Use a tilde followed by an asterisk sign for a case-insensitive regular expression match against a requested URI.
  • ^~: The tilde symbol is used to conduct the most extended non-regular expression match against the provided URI. No other matching operations are carried out if the requested URI encounters a matching location block.

Now that you’ve seen the modifiers that you can use to modify the performance of the location directive, let’s see how NGINX works with the location directive.

How Does NGINX Choose a Location Block?

You can specify a filesystem location by using a prefix string or a regular expression.

For instance, the “~*” modifier provides case-insensitive regular expressions, whereas the “~” modifier specifies case-sensitive regular expressions.

Similarly, to find a location match for a URI, NGINX first searches the locations specified using the prefix strings (without employing a regular expression). Following that, the locations containing regular expressions are verified in the order they were declared in the configuration file.

NGINX will perform the following steps to pick a location block for a URL.

  • NGINX begins by checking for an exact match indicated with location = /some/path/; if a match is discovered, this block is delivered immediately.
  • If no such exact location blocks exist, NGINX will match the longest non-exact prefixes, and if a match is discovered where the modifier has been applied, NGINX will stop searching, and this location block will be picked to fulfill the request.
  • If the matched longest prefix location lacks a modifier, the match is temporarily saved, and the following steps are executed:
    • NGINX now redirects the search to the location block containing the and * modifier and selects the first location block that matches the request URI to serve the request immediately.
    • If no blocks matching the requested URI are found in the preceding step, the previously saved prefix location serves the request.

NGINX Location Block Examples

Let’s now look at some examples of the NGINX location blocks that you can modify to fit your project’s requirements.

NGINX Location That Fulfills All Requests

The prefix location / in the following example will match all requests but will only be used as a last resort if no other matches are discovered.

NGINX Location That Fulfills All Requests

NGINX Location Matching the Exact URL

NGINX will always try to match the most specific prefix location first. As a result, the equal sign in the following location block demands an exact match with the specified route before terminating the search for more matches.

NGINX Location Matching the Exact URL

The above location block will match the URL https://example.com/redswitches but not the URLs https://example.com/redswitches/index.html or https://example.com/redswitches/.

NGINX Location Block for a Directory

The following location block will match any request beginning with /redswitches/ but will continue to look for a more precise location block for the requested URI. As a result, if NGINX cannot find a more exact match, the location block will be selected.

NGINX Location Block for a Directory

Example of NGINX Location RegEx

The modifier generates a case-sensitive regular expression match. As a result, the URI /redswitches or /redswitches/logo.png will be searched, but the process won’t continue searching once it finds a match.

NGINX Location RegEx

redswitches/css/js File Location Block in NGINX

The modifier * matches any request that ends with png, ico, gif, jpg, jpeg, css, or js (case-insensitive). Any queries to the /images/ folder, on the other hand, will be handled by the preceding location block.

File Location Block in NGINX

Case Sensitive NGINX Location RegEx Match

The ~ modifier in the following location block matches a case-sensitive regular expression but keeps looking for a better match.

Case Sensitive NGINX Location RegEx Match

NGINX Location RegEx Case Insensitive Match

The modifier ~* in the following location block provides a case-insensitive regular expression match, but the search for a better match continues.

NGINX Location RegEx Case Insensitive Match

NGINX Location Directive Best Practices

Now that you have a clear idea of how to use the NGINX location directive, it’s time to discuss some best practices you can use to streamline your NGINX location directives.

Pay Attention to the Order of the Location Blocks

The sequence of location blocks is critical because NGINX will process the request using the first location block that matches the request URI. As such, you must carefully arrange the location blocks to ensure a logical order for your application.

Specificity of Location Blocks

Make your location blocks as specific as possible to guarantee that NGINX can utilize the correct configuration directives for each request. If you have a location block that matches /user/123 and another that matches /user/(. ), ensure the /user/123 location block arrives first.

Regular Expression Performance

Remember that regular expressions may be slower than precise or prefix matches in the location blocks. To boost efficiency, utilize exact or prefix matches instead of regular expressions.

Conclusion

The NGINX location directive is handy for specifying separate configuration blocks for various URLs or URIs. Your NGINX server becomes more efficient by processing the response for specific URLs or URIs. We mentioned the best practices for writing location directives.

You need to remember to order the location blocks properly, be as detailed as possible, and minimize the use of regular expressions to improve efficiency. If you’re unsure how to do it, contact RedSwitches today.

RedSwitches understands the importance of server resources for optimal NGINX performance. You can depend on our engineers to advise you on selecting the right bare metal server specifications for your NGINX projects.

Contact us now to learn more.

FAQs

Q. Does the order of location blocks matter in NGINX?

Yes, it does. In addition, the directive’s context and the directives’ nesting also affect how NGINX interprets and applies the directives.

Q. What is a prefix location match in NGINX?

NGINX location matches based on the prefix (no regular expression). Each location will be compared to the requested URI. NGINX looks for an exact match. The location block is immediately picked if the a “= “modifier perfectly matches the request URI.

Q. What are location directive actions?

Location directives are rules that assist in identifying ‘pick and place’ locations for inventory movement. For example, in a sales order transaction, a location directive specifies where the products will be chosen and where they will be placed.

Q. Where is the NGINX location set directory?

Every NGINX configuration file is placed in the /etc/nginx/ directory, with the primary configuration file in /etc/nginx/nginx.conf.

Try this guide with our instant dedicated server for as low as 40 Euros