Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Abstract: Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Created: 2026-10-26 by
To expose a local server on a VPS while preserving real client IPs, configure your reverse proxy (such as Nginx or Apache) to forward the original client address via HTTP headers like X-Forwarded-For and X-Real-IP. You must then instruct your backend application to trust these headers and parse the first IP in the chain, ensuring that the OS-level logging reflects the true visitor rather than the VPS gateway.

Understanding the Proxy Chain

When you place a reverse proxy in front of your local server, the direct connection between the internet user and your application is broken. The proxy acts as an intermediary, accepting the incoming request from the client and forwarding it to your local service. By default, most web servers log the IP address of the immediate connection source. In this architecture, that source is your VPS, not the actual user. Consequently, your logs will show thousands of requests all originating from a single IP address, which destroys the utility of access logs for security auditing, rate limiting, and analytics. The solution lies in standard HTTP headers designed specifically for this purpose. When a proxy forwards a request, it can append the original client's IP to the X-Forwarded-For header. This header contains a comma-separated list of IPs: the original client, followed by each proxy the request passed through. Additionally, many proxies set the X-Real-IP header, which contains only the single IP address of the immediate previous hop. Your backend application needs to be configured to read these headers instead of relying solely on the socket connection details provided by the operating system.

Configuring Nginx as a Reverse Proxy

Nginx is one of the most common tools for this setup due to its performance and flexibility. To ensure Nginx passes the correct information to your backend, you need to modify the server block configuration for your domain. Inside the location block where you proxy the traffic, you must add specific directives to set the forwarded headers.
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        
        # Pass the real client IP
        proxy_set_header X-Real-IP $remote_addr;
        
        # Pass the full chain of IPs
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
        # Preserve the original Host header
        proxy_set_header Host $host;
    }
}
The directive proxy_set_header X-Real-IP $remote_addr tells Nginx to take the IP address of the person connecting directly to the VPS and place it into a new header named X-Real-IP. The proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for command is more robust because it appends the current client IP to any existing X-Forwarded-For header. If there was no previous header, it creates one with just the current IP. This ensures that if your request passes through multiple layers of proxies, the complete history is preserved. After making these changes, reload Nginx using sudo systemctl reload nginx to apply the new configuration without dropping active connections.

Configuring Apache as a Reverse Proxy

If you are using Apache, the process is similar but utilizes different modules. You will need the mod_proxy, mod_proxy_http, and mod_headers modules enabled. These modules allow Apache to act as a gateway and manipulate HTTP headers before sending them to the backend.
<VirtualHost *:80>
    ServerName example.com
    
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8080/
    ProxyPassReverse / http://127.0.0.1:8080/
    
    RequestHeader set X-Real-IP "%{REMOTE_ADDR}s"
    RequestHeader set X-Forwarded-For "%{REMOTE_ADDR}s"
</VirtualHost>
In Apache, ProxyPreserveHost On ensures that the Host header sent by the client is passed through unchanged, which is critical for virtual hosting. The RequestHeader directives manually inject the X-Real-IP and X-Forwarded-For headers. Note that unlike Nginx, Apache does not automatically append to X-Forwarded-For in older versions; you may need to use mod_remoteip for more advanced handling if you are behind multiple proxies. For simple setups, setting these headers explicitly is sufficient. Restart Apache with sudo systemctl restart apache2 after editing the configuration file.

Configuring the Backend Application

Setting up the proxy is only half the battle. Your backend application, whether it is written in Python, Node.js, PHP, or Java, must be configured to trust these headers. Most modern frameworks have built-in support for this, but it often requires explicit enabling for security reasons. For example, in Django (Python), you must add 'django.middleware.common.CommonMiddleware' to your middleware and set SECURE_PROXY_SSL_HEADER if you are also handling SSL termination. More importantly, you should ensure that your WSGI server (like Gunicorn or uWSGI) is configured to respect the HTTP_X_FORWARDED_FOR environment variable. In Node.js applications using Express, you typically need to set app.set('trust proxy', true) or specify the trust function to indicate that the application should trust the headers coming from the reverse proxy. Without this step, the application will ignore the headers and continue to log the VPS IP address.

Verifying the Configuration

To verify that your setup is working correctly, make a request to your site and check the access logs of your backend application. You should see the public IP address of your browser, not the private IP of your VPS. You can also use command-line tools like curl to inspect the headers being received by your backend. Run curl -I http://localhost:8080 (if testing locally) or check the raw request logs to confirm that X-Real-IP and X-Forwarded-For contain the expected values.

Frequently Asked Questions

Why do I still see the VPS IP in my logs?

This usually means your backend application is not configured to trust the proxy headers. Ensure that your framework has "trust proxy" enabled and that it is reading the X-Forwarded-For or X-Real-IP headers instead of the socket remote address.

Is it safe to trust X-Forwarded-For headers?

You should only trust these headers if they come from a proxy you control, such as your own Nginx or Apache instance. If users can send arbitrary headers directly to your backend, they could spoof their IP. Always ensure your reverse proxy strips or overrides these headers before passing them to the backend.

How does this affect SSL/TLS certificates?

Preserving client IPs is separate from SSL termination. If your reverse proxy handles SSL, it decrypts the traffic and forwards plain HTTP to your backend. This does not change how client IPs are logged, provided the proxy headers are correctly forwarded as described above.

Can I use this method with cloud providers like AWS or DigitalOcean?

Yes, but cloud providers often have their own load balancers or firewalls that may insert additional headers. You may need to configure your application to trust the specific IP ranges of the cloud provider's infrastructure to accurately identify the original client IP.

What if I am behind multiple proxies?

The X-Forwarded-For header supports chains by appending IPs. The last IP in the list is the original client, while earlier IPs are intermediate proxies. Your application should parse the rightmost IP in the comma-separated list to get the true client address.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More