NGINX URL Redirection

Saji asked:

In nginx we have been trying to redirect a URL as follows:
Client hits the url:

and nginx has to route the request to the back-end tomcat.


server configuration as follows:

server {
listen 80;
listen [::]:80;

server_name localhost;

location ~ ^/reg?(.*) {
            resolver x.x.x.x;
            proxy_pass http://localhost:8000/some_dir/reg?$1;

With the above settings I could able to see the requests are hitting the back-end tomcat while accessing from browser. But, URI strings after “reg?” ie.:"" aren’t getting directed.

Can someone help me point out whats wrong with the regex?

My answer:

The problem here is that location matches only the path component of a URL. So, as written, your regex matches many more URLs than you expect. For instance, it matches /re, /redwood, /regular as well as /reg. But it does not put the query string in the capture, because the query string is not part of the path component.

Fortunately, you don’t need a regex at all, nor do you need to capture the query string, as nginx already keeps track of it. Consider:

location /reg {
    proxy_pass http://localhost:8080/some_dir/reg$is_args$args;

Here we get rid of all the extraneous matches and match only URL paths beginning with /reg. You can make it more specific by using location = /reg instead. Then we pass the arguments explicitly.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.