user1767105
user1767105

Reputation: 2059

nginx location matching for url params only

I need to rewrite any root subdomain requests and append locale params if they aren't already there. e.g. -> de.example.com needs to be rewritten as -> de.example.com/?locale=de. then I proxy it off to the app.

2 questions:

1) is this the correct approach? or should I be using regex instead here? (new to this so if other problems, please lmk)

2) is there a way to log things inside the location block? Having trouble getting same config working on another server, logging would help. (e.g logging what args is if it isn't matching, or if it matches on another location block). It only needs to happen on the root page so this is my current config

#existing default (nonsubdomain block)
server {
 server_name _;
 root /var/www/web_app;
 try_files $uri/index.html $uri.html $uri @app;
 location @app {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app_server;
      }
}

#just added for subdomain 
server {

  server_name de.example.com;
  root /var/www/web_app;

  location / {
  try_files $uri/index.html $uri.html $uri @app;
 }  
  location @app {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://app_server;
  }
  location = / {
   if ($args != locale=de ){ 
    rewrite ^ $scheme://de.example.com/?locale=de permanent;
    }
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://app_server;
  }
}

Upvotes: 0

Views: 6967

Answers (1)

VBart
VBart

Reputation: 15110

1) is this the correct approach? or should I be using regex instead here? (new to this so if other problems, please lmk)

You should use $arg_locale != de instead of $args != locale=de. Look at the docs: http://nginx.org/en/docs/http/ngx_http_core_module.html#var_arg_

2) is there a way to log things inside the location block? Having trouble getting same config working on another server, logging would help. (e.g logging what args is if it isn't matching, or if it matches on another location block). It only needs to happen on the root page so this is my current config

Debug log: http://nginx.org/en/docs/debugging_log.html

Upvotes: 1

Related Questions