How to use if in Nginx | Nginx Conditions


One of the most important things to learn when managing a Web server is conditionals. Here we talk about how to use if in Nginx.

Specification:

OS Version: Ubuntu Os 18.04.3 (LTS) x64
Nginx version: nginx/1.14.0

The most common conditional is “if” and there is a catch with it. You can read more about it in this article about it, the idea is to use “if” outside the “location” block and not within it. 

Without any further ado, let’s see how “if” is used in different scenarios:

  • Return status code 405 (Not Allowed) for a POST request:
location / {
                proxy_cache my_zone;
                proxy_pass http://bluegrid.io;
                proxy_cache_valid 200 1d;
 
                if ($request_method = POST ) {
                        return 405;
                }
        }

Let’s test out how it works:

bluegrid-edu:~# curl -I http://bluegrid.io/ -X POST
HTTP/1.1 405 Not Allowed
Server: nginx/1.14.0 (Ubuntu)
Date: Sun, 26 Jul 2020 12:58:39 GMT
Content-Type: text/html
Content-Length: 182
Connection: keep-alive
  • Redirect request with query string “p=66” (random example):
location / {
                proxy_cache my_zone;
                proxy_pass http://bluegrid.io;
                proxy_cache_valid 200 1d;
 
                if ($args ~ p=66){
                        rewrite ^ http://bluegrid.io/ permanent;
                }
        }

And let’s see it in works:

bluegrid-edu:~# nano /etc/nginx/sites-available/default 
root@bluegrid-edu:~# curl -I http://bluegrid.io/?p=66
HTTP/1.1 301 Moved Permanently
Server: nginx/1.14.0 (Ubuntu)
Date: Sun, 26 Jul 2020 13:07:40 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: http://bluegrid.io/?p=66
  • Now let’s try returning response header “Test” with value “passed” if the request header was “Testing: 1”:
location / {
                proxy_cache my_zone;
                proxy_pass http://bluegrid.io;
                proxy_cache_valid 200 1d;
 
                if ($http_testing = '1') {
                        add_header Test passed;
                }
        }

And now to confirm it works:

bluegrid-edu:~# curl -I http://bluegrid.io/ -H 'Testing: 1'
HTTP/1.1 200 OK
Server: nginx/1.14.0 (Ubuntu)
Date: Sun, 26 Jul 2020 13:16:12 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 55223
Connection: keep-alive
Last-Modified: Sun, 26 Jul 2020 11:04:46 GMT
ETag: "d7b7-5ab562c93193f"
Vary: Accept-Encoding
Referrer-Policy: no-referrer-when-downgrade
Test: passed
Accept-Ranges: bytes
Share this post

Share this link via

Or copy link