Two Subdomains on Same Public IP but Two Different Webservers

Abstract: Configure Apache Name-Based Virtual Hosts and reverse proxies to host multiple subdomains on a single public IP.

Created: 2026-08-20 by
You can host multiple websites on a single public IP address by configuring Apache HTTP Server with Name-Based Virtual Hosts. This technique allows the web server to distinguish between requests for different subdomains based on the hostname provided in the HTTP header, directing traffic to the correct document root and backend application without requiring separate IP addresses.

Understanding Name-Based Virtual Hosting

The core mechanism enabling this setup is called Name-Based Virtual Hosting. When a client connects to your server’s IP address, it sends an HTTP request that includes a Host header specifying which domain or subdomain it wants to access. Apache reads this header before processing the request and matches it against its configured virtual hosts. If a match is found, Apache serves content from the corresponding directory; if not, it falls back to a default configuration. This method is efficient because it eliminates the need for expensive additional IP addresses while maintaining complete isolation between different sites hosted on the same machine.

Configuring Apache Virtual Hosts

To implement this, you must create distinct configuration files for each subdomain. Start by creating a new file in the /etc/apache2/sites-available/ directory for each subdomain you wish to host. For example, create site1.conf for app.example.com and site2.conf for api.example.com. Each file should define a <VirtualHost> block listening on port 80 (and optionally 443 for HTTPS). Inside this block, specify the ServerName directive to match the subdomain exactly. Set the DocumentRoot to point to the specific directory where the website files are stored. Ensure that the permissions for these directories allow the Apache user to read the files. After saving the configuration files, enable them using the a2ensite command for each new site. This step creates symbolic links in the sites-enabled directory, making the configurations active for the server.

Resolving Port Conflicts and Service Binding

A common challenge arises when the two webservers are not both standard Apache instances but perhaps one is running a Node.js application, a Python Flask app, or a Docker container. In such cases, you cannot have both services listening directly on port 80 or 443 of the public IP. Instead, configure your primary Apache instance as a reverse proxy. Use the ProxyPass and ProxyPassReverse directives within the virtual host block to forward requests to the internal port where the secondary web server is running. For instance, if your Node.js app runs on localhost:3000, you would map app.example.com to http://localhost:3000. This approach ensures that Apache handles the incoming HTTPS/TLS termination and routing, while the backend service remains isolated on a non-standard port. You may encounter issues if the backend service is not bound to 127.0.0.1 correctly, so verify your local firewall rules. If you suspect network connectivity issues between the proxy and the backend, consult our guide on Why I Can't Access My Web Service on Port 80 to troubleshoot binding errors.

DNS and SSL Configuration

Before testing the virtual hosts, ensure your DNS records are correctly configured. Both subdomains must resolve to the same public IP address via A records. Without proper DNS resolution, the browser will never send the correct Host header to Apache, resulting in 404 errors or the wrong site being displayed. If you plan to use HTTPS, which is mandatory for modern browsers, you need SSL certificates for each subdomain. You can obtain free certificates using Let's Encrypt via Certbot. Run Certbot for each domain separately, or use the --dry-run flag to test the process. Ensure that the SSLEngine on directive is present in your virtual host configurations if you are managing certificates manually. Pay attention to certificate name constraints; some older setups might fail if the SAN (Subject Alternative Name) does not include the specific subdomain. If you experience issues with redirect loops during SSL setup, check your .htaccess rules carefully, as incorrect redirects can cause browsers like Firefox to get stuck. For more details on fixing redirect loops, refer to Firefox Stuck on .htaccess Redirect? How to Fix It.

Testing and Troubleshooting

After applying all changes, restart Apache to load the new configurations. Use the command systemctl restart apache2 on Debian-based systems or service httpd restart on Red Hat-based systems. Before restarting, always run apache2ctl configtest to validate the syntax of your configuration files. This prevents downtime caused by syntax errors. Once restarted, use tools like curl -I http://subdomain.example.com to inspect the response headers and confirm that the correct virtual host is serving the request. Check the Apache error logs located in /var/log/apache2/error.log if you encounter permission denied errors or missing files. Remember that changing ports or listen directives in httpd.conf can sometimes lead to unexpected behavior if not aligned with your virtual host definitions. If you find that your port changes are not taking effect, review our article on Changing port in Apache httpd.conf listen not working to understand how Apache prioritizes configuration sources. Properly isolating your subdomains ensures that a crash or security issue in one web server does not compromise the other, providing a robust and scalable hosting environment.

Frequently Asked Questions

Can I host more than two subdomains on the same IP?

Yes, Apache supports any number of virtual hosts on a single IP address as long as they have unique ServerName directives. There is no hard limit imposed by the protocol itself, though system resources like memory and file descriptors may eventually become a bottleneck for thousands of sites.

What happens if a request does not match any virtual host?

Apache will serve content from the first virtual host defined in its configuration order, often referred to as the default virtual host. To prevent accidental exposure of sensitive data, it is best practice to configure a strict default host that returns a 403 Forbidden error or redirects to a main landing page.

Do I need separate SSL certificates for each subdomain?

While you can obtain individual certificates for each subdomain, it is more efficient to use a Single Certificate with Subject Alternative Names (SAN) or a Wildcard Certificate (*.example.com). This reduces management overhead and simplifies renewal processes for Let's Encrypt users.

How do I debug why my subdomain shows the wrong site?

Use curl -H "Host: subdomain.example.com" http://127.0.0.1 to simulate a request directly to the server. This bypasses DNS issues and confirms whether Apache is routing the request to the correct document root based on the hostname header alone.

Is it safe to run different web frameworks on the same server?

It is safe provided you isolate the processes correctly using reverse proxies and set appropriate file permissions. Avoid running backend services as the root user and ensure that each framework listens only on localhost interfaces to prevent direct external access bypassing Apache.

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