Nginx Reverse Proxy – How to Perform URL Rewrite

nginxrewrite

I would like to rewrite the URL in a reverse proxy so that it removes the first segment but leaves any following segments intact. I need this to happen before it hits the proxy pass.

Example:

/admin/auth/local ----> (REWRITES TO) /auth/local
/admin/auth/register -------> (REWRITES TO) /auth/register

My Location block:

  location /admin {
        #add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
        add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
        proxy_set_header Host $host;
        proxy_set_header X-Real-Ip $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass_header Set-Cookie;
        proxy_read_timeout                 30;
        proxy_buffers 64 8k;
        rewrite /admin / break;
        proxy_pass http://127.0.0.1:9000;

I tried the following with no luck:

rewrite /admin / break;

Best Answer

There are two parts here. First one is how nginx routes incoming requests via proxy_pass.

There one can map incoming requests for / to backend with /admin/ prefix with the following configuration:

location / {
    proxy_pass http://127.0.0.1:9000/admin/;
}

No rewrite statement is needed.

Second part is the URLs that are generated by the application that is running at 127.0.0.1:9000. You need to configure that application to generate URLs without the /admin prefix to have URLs that match nginx routing setup.

Nginx cannot reliably do this change on the content generated by the backend.

Related Topic