nginx catch all location

NGINX Catch All Location

NGINX is a powerful web server used by many websites and organizations. It allows you to configure location blocks to handle different types of URLs. But sometimes you may want to configure catch all location block to handle all requests whose URLs do not match any of the existing location blocks.


How to Configure NGINX Catch All Location

Typically, here is how we configure various location blocks in NGINX.

server {
     ...
     location /location1 {
              do something;
     }
     location /location2 {
              do something;
     }
     location /location3 {
            /do something
     }
}

In this case, NGINX will respond as long as the incoming request matches location1, location2 or location3. For all other incoming requests, it will return 404 page not found response.

But sometimes you may want to catch such requests and respond with a proper response, such as redirect them to your home page.

In this case, you need to add the following ‘location / ‘ block (shown in bold) to catch all location requests that are not caught by any other location block.

server {
    location / {
        # catch all unless more specific location match
    }

    location /location1 {
        # do something
    }

    location /location2 {
        # do domething
    }

    location /location3 {
        # do domething
    }
}

In the above configuration, if the incoming request does not match location1, location2, and location3 then they will be handled by ‘location /’ block. In this block you can direct users to home page, or to some other page that helps them navigate your website better.

If you want ‘/’ to match to something specific and let everything else be caught by catch all location, then you need to create a separate ‘location = / ‘ block.

server {
    location / {
        # catch all except those matching /, location1, location2, location3
    }

    location = / {
        # catch / specifically
    }

    location /location1 {
        # do something
    }

    location /location2 {
        # do domething
    }

    location /location3 {
        # do domething
    }
}

In this article, we have learnt how to configure catch all location in NGINX. You can customize it as per your requirement.

Also read:

How to Download Images in Python
How to Remove Trailing Newline in Python
How to Pad String in Python
How to Get Size of Object in Python
How to Import from Parent Folder in Python

Leave a Reply

Your email address will not be published.