Reenvío de encabezados y dirección IP del cliente
Aprenda cómo Nginx reescribe los encabezados de solicitud al actuar como proxy y cómo conservar la información original del cliente para las aplicaciones upstream.
Reenvío de encabezados y dirección IP del cliente es una lección gratuita de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Why Headers Matter
When Nginx acts as a reverse proxy, the upstream server only sees a connection coming from Nginx, not the real client. Without extra configuration, the backend loses the visitor's original IP, host, and protocol.
To keep this information, Nginx must forward headers describing the original request.
The Default Host Header
By default Nginx may pass the upstream server's address as the Host header. Many apps rely on the original host for routing or building absolute URLs.
Set it explicitly so the backend sees what the client requested:
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
}Preserving the Real Client IP
The X-Real-IP header carries the original client's address so the backend can log or rate-limit by real visitor.
$remote_addrholds the connecting client's IP
proxy_set_header X-Real-IP $remote_addr;X-Forwarded-For Chain
X-Forwarded-For is a comma-separated chain of every proxy a request passed through. The variable $proxy_add_x_forwarded_for appends the current client to any existing value.
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;Forwarding the Protocol
If TLS terminates at Nginx, the backend speaks plain HTTP and cannot tell the original scheme. Send X-Forwarded-Proto so it can build correct https URLs and set secure cookies.
proxy_set_header X-Forwarded-Proto $scheme;Putting It Together
A standard reverse-proxy block bundles all four headers. This is the baseline you will reuse across nearly every project.
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}Reusing Header Config
Repeating the same headers in every location is error prone. Put them in an include file and pull it in wherever needed.
# /etc/nginx/proxy_headers.conf
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# in a server/location block:
include /etc/nginx/proxy_headers.conf;Trusting Forwarded Headers Safely
Clients can spoof X-Forwarded-For. Only trust it from known proxies. Use the real_ip module to set the true client IP from trusted upstreams.
set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;
real_ip_recursive on;Removing or Clearing Headers
You can strip a header by setting it to an empty string. This is useful to hide internal headers from upstream or to prevent leaking server identity.
proxy_set_header X-Powered-By "";
proxy_hide_header X-Powered-By;Passing Custom Headers
You can inject your own headers to give the backend extra context, such as a tag identifying which gateway handled the request.
proxy_set_header X-Gateway-Node "edge-1";
proxy_set_header X-Request-Start $msec;Verifying the Result
Test from a backend that echoes headers (or use an inspector endpoint). You should see X-Real-IP matching your machine and X-Forwarded-Proto matching the scheme you used.
curl -H "Host: example.com" http://localhost/headersQuick Check
Which Nginx variable appends the current client to an existing forwarding chain?
Recap
You learned how Nginx rewrites requests and how to keep client context intact:
Hostpreserves the requested domainX-Real-IPandX-Forwarded-Forcarry the client IPX-Forwarded-Protoreports the original scheme- Use
real_ipand trusted ranges to avoid spoofing
These headers are the foundation of a transparent, secure reverse proxy.
Preguntas frecuentes
¿La lección «Reenvío de encabezados y dirección IP del cliente» es gratis?
Sí — el texto completo de «Reenvío de encabezados y dirección IP del cliente» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway), actualiza a CoddyKit PRO. El curso de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) incluye 4 lecciones en total.
¿Qué aprenderé en «Reenvío de encabezados y dirección IP del cliente»?
Aprenda cómo Nginx reescribe los encabezados de solicitud al actuar como proxy y cómo conservar la información original del cliente para las aplicaciones upstream. Practicas API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)?
No se requiere experiencia previa. API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Reenvío de encabezados y dirección IP del cliente»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)?
Sí. Cada lección de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Configuración de un proxy inverso sencillo
- Servidores upstream y balanceo de carga
- Almacenamiento en búfer y caché del proxy
- Reenvío de encabezados y dirección IP del cliente