3

Tomcat 8 URL rewrite is not working when requests are proxy passed from nginx server. But the same url-rewrite is working when requests are directly served from tomcat server.

I am having nginx server listening to 80 port and tomcat server listening to 9080 port.

nginx proxy-pass configuration

http 
{
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server 
    {
        listen       80;
        location /app/ 
        {
            proxy_pass http://localhost:9080/;
            proxy_set_header Host $host:$server_port;
        }
    }
}

tomcat rewrite.config file

RewriteRule ^app/xyz    /app/abc        [L]

When I try to access the url http://server-name/app/xyz, the URL rewriting is not working. But when accessed directly via tomcat listening port(server-name:9080/app/xyz) it is working.

EDIT

Previously I had the URL rewriting configured in nginx.

nginx url rewrite configuration

location /app/ 
{
        proxy_pass http://localhost:9080/;
        proxy_set_header Host $host:$server_port;
        include /dev_resource/nginx/rewrite.conf;
} 

nginx rewrite.conf

rewrite ^/app/xyz       /app/abc        break;

When I try to access the url http://server-name/app/xyz, the url rewriting is working. The request is not being forwarded to http://server-name/xyz.

But when url rewriting is configured with tomcat 8, the url http://server-name/app/xyz is being forwarded to http://server-name/xyz.

1 Answers1

1

The proxy_pass directive may or may mot rewrite the URI, depending on its parameter and the surrounding location directive.

This location and proxy_pass combination will map URIs like /app/xxx to /xxx upstream:

location /app/ {
    proxy_pass http://localhost:9080/;
}

In order to pass URIs upstream transparently, remove the URI element from the proxy_pass directive (including the /):

location /app/ {
    proxy_pass http://localhost:9080;
}

So, in answer to your first question (before the EDIT), the reason Tomcat did not rewrite the URI was because there were no URIs being received that matched the rule. That is, no URIs that started with /app/ because proxy_pass had already removed that prefix.

In answer to your second question (after the EDIT), the nginx rewrite sees the URI before it is changed by proxy_pass. So the URI /app/xyz is mapped to /app/abc by the rewrite directive, then mapped to /abc by the proxy_pass directive before being sent upstream. So, Tomcat receives /abc.

In conclusion, if Tomcat should be seeing URIs beginning with /app/, then you need to fix the proxy_pass directive (as shown above), and then rewrite will work the same in both the front-end and the back-end.

However, if Tomcat should be seeing URIs with the /app prefix removed, then any rewrite rules in Tomcat should not include the /app prefix in the match regex.

Richard Smith
  • 45,711
  • 6
  • 82
  • 81