I am trying to set up a Nginx reverse proxy for accessing an API located at port 3000, inside a Docker container.
The proxy works fine for many kinds of urls, including those with escaped characters such as %20
(white space), %3C
(<), %3E
(>), etc. However, when it comes to the character %2F
(/), Nginx decodes it before forwarding the request to the corresponding server.
For instance, the URL:
https://example.com/api/August%2F2021/games/desc/
becomes:
https://example.com/api/August/2021/games/desc/
,
thus returning a 400 bad request.
This is my nginx.conf
:
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
server {
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/haxmania.com.br/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/haxmania.com.br/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
server_name example.com; # managed by Certbot
location / {
root /app;
index index.html;
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://backend:3000/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
server {
if ($host = example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
server_name example.com;
return 404; # managed by Certbot
}
}
My question is almost identical to this one, however none of the solutions worked for me. I tried changing from:
proxy_pass http://backend:3000/;
to proxy_pass http://backend:3000$request_uri;
but it didn't not work.
I believe the solution might be writing a rewrite
directive, but I am struggling on how exactly this should be done... Any tips would be appreciated.