Skip to main content

Nginx

browser ->awslb->nginx->tomcate then abvoe ip addres about
Browser → AWS Load Balancer (ALB/ELB) → Nginx → Tomcat (Spring Boot)

इस chain में जब request आती है,
तो Spring Boot तक पहुँचते-पहुँचते client का original IP (जैसे 192.168.x.x या 49.x.x.x)
खो जाता है — क्योंकि हर proxy या load balancer request को forward करता है।


🧩 Problem:

अगर तुम request.getRemoteAddr() Spring Boot controller में log करते हो
तो ये IP Nginx या Load Balancer का IP देता है ❌
Client (Browser) का real IP नहीं।


✅ Solution: "Forwarded Headers" को सही तरीके से handle करना

🧱 Step-by-step Setup:


1️⃣ AWS Load Balancer Config (ALB/ELB)

ALB automatically जोड़ता है ये header 👇

X-Forwarded-For: <client-ip>, <proxy1>, <proxy2>...

इसलिए आगे Nginx को इसे forward करने देना ज़रूरी है।


2️⃣ Nginx Configuration

अपनी Nginx config file खोलो
(आमतौर पर /etc/nginx/sites-available/default या /etc/nginx/conf.d/app.conf)

sudo nano /etc/nginx/sites-available/default

फिर location block में ये lines डालो 👇

location / {
    proxy_pass http://localhost:8080;  # Tomcat/Spring Boot backend
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;            # Nginx client IP
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # full chain
    proxy_set_header X-Forwarded-Proto $scheme;
}

🔹 इससे Nginx client का original IP Spring Boot तक भेजेगा।


3️⃣ Spring Boot Application में सही IP निकालना

अब controller में ये कोड लगाओ 👇

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IPController {

    @GetMapping("/client-ip")
    public String getClientIp(HttpServletRequest request) {

        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return "Client IP: " + ip;
    }
}

👉 यह क्रम में जांचता है:

  1. X-Forwarded-For (AWS + Nginx से)

  2. X-Real-IP (Nginx से)

  3. request.getRemoteAddr() (fallback)


4️⃣ Optional (Spring Boot Config)

अगर तुम Spring Boot 3+ version यूज़ कर रहे हो,
तो application.yml में ये सेटिंग helpful है 👇

server:
  forward-headers-strategy: native

इससे Spring खुद X-Forwarded-* headers को auto-handle करता है।


✅ अब Output Example

LayerIP shown
Browser (real client)49.36.72.110
AWS Load BalancerAdds header: X-Forwarded-For: 49.36.72.110
NginxForwards same header to Tomcat
Spring BootDetects and logs → 49.36.72.110

अगर चाहो तो मैं तुम्हें इस setup का
end-to-end working diagram + config files (nginx + spring) बना दूँ
जिससे पूरा flow visual रूप में समझ आ जाए?

You said:

Yes

ChatGPT said:

बहुत बढ़िया Manoj 👍
अब नीचे मैं तुम्हें पूरे end-to-end setup का visual + configuration explanation दे रहा हूँ —
जिससे तुम easily समझ सको कि Browser से लेकर Spring Boot तक real client IP कैसे पहुँचेगा।


🌐 Architecture Diagram (Request Flow)

┌────────────┐
│  Browser   │
│  (Client)  │
│  IP: 49.x  │
└─────┬──────┘
      │ HTTP Request
      ▼
┌───────────────┐
│ AWS Load Balancer│
│ Adds Header:      │
│ X-Forwarded-For:  │
│ 49.x              │
└─────┬─────────────┘
      │ Forward request
      ▼
┌────────────┐
│   NGINX    │
│ /etc/nginx/sites-available/default │
│ Forwards headers again →           │
│ X-Forwarded-For, X-Real-IP         │
└─────┬──────┘
      │ proxy_pass
      ▼
┌────────────┐
│  Tomcat /  │
│ Spring Boot│
│ Application│
│ Reads headers & logs real IP       │
└────────────┘

⚙️ Step-by-Step Setup

🧩 1️⃣ AWS Load Balancer (ALB/ELB)

AWS by default adds:

X-Forwarded-For: <Client-IP>, <AWS-LB-IP>
X-Forwarded-Proto: http/https

इसलिए NGINX को ये header pass through करना होगा।


⚙️ 2️⃣ NGINX Configuration

File path:

sudo nano /etc/nginx/sites-available/default

Add or update this section:

server {
    listen 80;
    server_name _;

    location / {
        proxy_pass http://localhost:8080;  # Tomcat/Spring Boot 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;
    }
}

✅ Explanation:

DirectiveDescription
proxy_passRequest Tomcat को भेजता है
X-Real-IPNGINX client IP देता है
X-Forwarded-ForFull IP chain भेजता है
X-Forwarded-ProtoHTTP या HTTPS भेजता है

🧱 3️⃣ Spring Boot Setup

application.yml

server:
  port: 8080
  forward-headers-strategy: native

Controller Example:

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ClientInfoController {

    @GetMapping("/client-info")
    public String getClientInfo(HttpServletRequest request) {
        String ip = getClientIp(request);
        String userAgent = request.getHeader("User-Agent");
        String referer = request.getHeader("Referer");
        String protocol = request.getScheme();

        return """
                Client IP: %s
                User-Agent: %s
                Referer: %s
                Protocol: %s
                """.formatted(ip, userAgent, referer, protocol);
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            // If multiple IPs, take first (real client)
            return ip.split(",")[0];
        }
        ip = request.getHeader("X-Real-IP");
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}

📊 Output Example

HeaderExample Value
X-Forwarded-For49.36.72.110, 10.0.1.12, 172.31.22.5
X-Real-IP49.36.72.110
User-AgentMozilla/5.0 (Windows NT 10.0; Win64; x64)
Refererhttps://myapp.example.com/dashboard

Spring Output:

Client IP: 49.36.72.110
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Referer: https://myapp.example.com/dashboard
Protocol: https

🧾 4️⃣ Optional – Security Tip

अगर तुम चाहते हो कि कोई भी fake X-Forwarded-For header ना भेज सके,
तो NGINX में ये डालो:

real_ip_header X-Forwarded-For;
set_real_ip_from 127.0.0.1;
set_real_ip_from <AWS-LB-PRIVATE-IP>;
real_ip_recursive on;