Link Search Menu Expand Document
Table of contents

Simple redirect

server {
    listen 80;
    server_name 198.255.25.1;
    root /sites/demo; 

    location /logo {
        return 307 /example.png; 
    }
}

Rewrite rule 1

server {
    listen 80;
    server_name 198.255.25.1;
    root /sites/demo; 

    location /logo.png {
        rewrite ^/user/(\w+) /hello/$1;
        # $1 = (\w+) 
        # Req URL: https://domain.com/user/whatever >> https://domain.com/hello/whatever
    }
}

Rewrite rule 2

server {
    listen 80;
    server_name 198.255.25.1;
    root /sites/demo; 

    location /logo.png {
        rewrite ^/hello/whatever /thumb.png;
        # Req URL: https://domain.com/hello/whatever >> https://domain.com/thumb.png
    }
}

Rewrite rule 3

server {
    listen 80;
    server_name 198.255.25.1;
    root /sites/demo; 

    rewrite ^/hello/user /thumb.png last;
    # using `last` syntax to stop further rules
    
    location /hello { 
        return 200 "hello user"; 
    } 
    location = /hello/user {
        return 200 "hello user"; 
    } 
}

Rewrite rule 4 - http to https including query string

server {
        listen 80;
        server_name *.example.com;

        if ($http_x_forwarded_proto = "http") { return 301 https://$host$request_uri; }
        rewrite ^(.*[^/])$ $1/ permanent;
}