ParallelZebra
ParallelZebra

Reputation: 145

How do I rewrite request_uri variable in a location match

Java backend give me several interfaces like:

/admin/login
/client/query 
/agent/update 

I am a frontend engineer and I have to use these interfaces with ajax. Because we will deploy our projects on the same server, so I need to use a nginx proxy to direct those ajax request to the java service. But as you can see the interfaces start with different paths, so I prefixed them with "/api" in my code, and also configure nginx as below

axios.post('/api/admin/login'),
axios.post('/api/client/query'),
axios.post('/api/agent/update')

location /api {
    proxy_pass http://127.0.0.1:8080$request_uri;
    proxy_set_header Host 127.0.0.1;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

here my problem come:

Actually the java service get the request path: /api/admin/login, not /admin/login, so they can not handle that request. Can I rewrite my request_uri in nginx so that java get requests without /api prefix?

Upvotes: 0

Views: 1507

Answers (2)

Ivan Shatsky
Ivan Shatsky

Reputation: 15468

You don't need any rewrites for this. Use following location block:

location /api/ {
    proxy_pass http://127.0.0.1:8080/;
    proxy_set_header Host 127.0.0.1;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

See more info about slashes in proxy_pass directive here.

Upvotes: 1

Rastalamm
Rastalamm

Reputation: 1782

Copy pasted and adapted from a different question but should do the trick.

location /api {
 rewrite ^/api(/.*)$ $1 last;
}

Upvotes: 0

Related Questions