User Tools

Site Tools


Example of redirect and rewrites

Redirect root path

Redirect from to first then to some proxy app.

This will preserve any URI after, for example

will become

The option with using return directive is faster.

upstream ups {
    server fail_timeout=10s max_fails=3;
server {
    listen 80;
    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_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/";

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


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