User Tools

Site Tools


wiki:nginx_redirect_rewrites

Example of redirect and rewrites

Redirect root path

Redirect from example.com to example.com/it first then to some proxy app.

This will preserve any URI after example.com, for example

example.com/images/image1.png

will become

example.com/it/images/image1.png

The option with using return directive is faster.

upstream ups {
    server 127.0.0.1:3010 fail_timeout=10s max_fails=3;
}
 
server {
    listen 80;
    server_name example.com;
 
    access_log /var/log/nginx/ups_access.log;
    error_log /var/log/nginx/ups_error.log notice;
 
    location / {    
        return 301 /it$request_uri;
 
        # alternative using rewrite
        # rewrite ^/?(.*?)$ http://$host/it/$1 break;
        # rewrite_log on;
    }
 
 
    location /it {
        proxy_pass http://ups;
        proxy_set_header Host $host;
    }
}

You can check the rewrite messages in specified error log.

Redirect based on browser's Accept-Language header that is sent

server conf:

   location / {
        return 301 /$lang/$request_uri;     
    }
 
    location /it {
        proxy_pass http://ups;
        proxy_set_header Host $host;
    }
 
    location /en {
        proxy_pass http://127.0.0.1:3000/;
        proxy_set_header Host $host;
    }

In http context add the mapping for $lang, e.g.

http {
        ...
 
        map $http_accept_language $lang {
                default en;
                ~it it;
                ~es es;
                ~fr fr;
        }
 
        ...
 
}

Rewrite uppercase to lowercase

Install perl module first:

apt install nginx-module-perl

Enable it in nginx.conf near top of file, outside of any section

load_module "modules/ngx_http_perl_module.so";

Create perl rewrite function inside http section:

# Include the perl module
perl_modules perl/lib;
 
# rewrite function from upper to lowercase
perl_set $uri_lowercase 'sub {
  my $r = shift;
  my $uri = $r->uri;
  $uri = lc($uri);
  return $uri;
}';

Use it in site configuration, maybe put it at end of file to not interfere with other routes (test this for your own setup)

# if the path contains uppercase characters,
# rewrite to lowercase
location ~ [A-Z] {
   rewrite ^(.*)$ $scheme://$host$uri_lowercase;
}

Tested on

  • Debian 11
  • nginx/1.23.1

See also

References

wiki/nginx_redirect_rewrites.txt · Last modified: 2023/01/11 14:43 by antisa

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki