Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › DevOps

How to Point Subdomains to Specific Ports With Nginx

By Freedom251 Team · · 11 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

DNS cannot point a subdomain to port 3000, 8080, or any other application port. DNS records map a name to an IP address or another hostname. Nginx receives the request on public port 80 or 443, chooses a virtual host from the requested subdomain, and then proxies the request to the correct internal port.

For example, app1.example.com can resolve to the same server as app2.example.com. Nginx can route the first hostname to 127.0.0.1:3000 and the second to 127.0.0.1:8080, while visitors use clean URLs without typing either backend port.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The three layers of subdomain-to-port routing

A working deployment separates name resolution, public listening, and backend forwarding:

  1. DNS resolves each subdomain to the public IPv4 address, IPv6 address, or alias of the Nginx host.
  2. Nginx listens on a public address, normally port 80 for HTTP and 443 for HTTPS. Its server_name directive matches the hostname supplied by the browser.
  3. proxy_pass sends the matched request to the application listening on a private address and port, such as http://127.0.0.1:3000.

The port is selected by Nginx, not by an A, AAAA, or CNAME record. A URL can include a nonstandard port explicitly—for example, https://app1.example.com:8443—but that is a different design: the client must reach that public port, and the firewall and Nginx listener must expose it. The usual reverse-proxy pattern exposes only 80 and 443 and keeps application ports private.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
Layer What it decides Typical setting
DNS Which host receives traffic for a name A, AAAA, or CNAME record
Nginx listener Which public protocol and port accept traffic listen 80; or listen 443 ssl;
Virtual host Which configuration matches the hostname server_name app1.example.com;
Reverse proxy Which application receives the request proxy_pass http://127.0.0.1:3000;

Step 1: Create DNS records for each subdomain

At the authoritative DNS provider for example.com, create one record for every hostname you want Nginx to serve. The record value should identify the Nginx machine, not an application’s private listening address.

A records for IPv4

Create an A record with the subdomain label as its name and the Nginx server’s public IPv4 address as its value:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Name Type Value Purpose
app1 A Your Nginx host’s public IPv4 address Resolves app1.example.com
app2 A Your Nginx host’s public IPv4 address Resolves app2.example.com

AAAA records for IPv6

If the Nginx host has a publicly reachable IPv6 address, add an AAAA record for each name. Do not publish an IPv6 address unless Nginx is listening on IPv6 and the firewall permits the intended traffic. A browser that prefers IPv6 can otherwise fail even though IPv4 works.

CNAME records for aliases

A CNAME makes a subdomain an alias of another fully qualified domain name. Use it when the DNS provider or hosting design gives you a hostname to follow instead of a fixed address. A CNAME still does not carry a port; the final host must resolve to the machine that accepts the request.

Verify DNS before changing Nginx

Check that both names resolve to the Nginx host:

dig app1.example.com A
dig app1.example.com AAAA
dig app2.example.com A
dig app2.example.com AAAA

Compare the returned addresses with the server’s public IPv4 and IPv6 addresses. If a result points directly at an application that is bound only to a private address, Nginx will never receive that request. DNS propagation time depends on the record’s TTL and resolver caches, so test the authoritative result and your normal client resolver separately.

Step 2: Make sure each application is listening

Before writing a proxy block, confirm the service and port exist on the Nginx host or on a private network reachable from it. For local services, a listening socket check is useful:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ss -ltnp

Look for the expected port, such as 127.0.0.1:3000 or 0.0.0.0:8080. Binding an application to 127.0.0.1 keeps it reachable only from the same machine, which is appropriate when Nginx runs there. If Nginx and the application are on separate machines, use the application’s private network address and restrict that network with firewall rules.

Test an HTTP backend directly from the Nginx host before involving DNS:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
curl -i http://127.0.0.1:3000
curl -i http://127.0.0.1:8080

A refusal, timeout, or unexpected protocol at this stage must be fixed in the application or network before Nginx can proxy it.

Step 3: Create one Nginx server block per subdomain

The clearest arrangement is one server block for each hostname. Both blocks can listen on port 80; Nginx uses the incoming Host header to select the matching server_name.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    server_name app1.example.com;

    location / {
        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;
        proxy_pass http://127.0.0.1:3000;
    }
}

server {
    listen 80;
    server_name app2.example.com;

    location / {
        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;
        proxy_pass http://127.0.0.1:8080;
    }
}

Replace the names and ports with your real values. The location / block catches every path under the hostname. The proxy_pass address includes the backend protocol, host, and port; it belongs inside a location context.

Why separate blocks are preferable

  • Each hostname has an unambiguous destination and certificate configuration.
  • Access and error logs can be separated per application.
  • Redirects, request limits, WebSocket settings, and maintenance pages can be changed independently.
  • A mistake in one application’s port is less likely to affect another virtual host.

You can use wildcard names for families of subdomains, but exact names are easier to audit. If several blocks share a listen address and no server_name matches, Nginx sends the request to the default server for that port. An unexpected welcome page often indicates a hostname mismatch or an unintended default block.

How Nginx chooses the destination

listen controls the public endpoint

listen 80; accepts HTTP on port 80. It does not mean the application must use port 80. The backend can be on any reachable port. For encrypted traffic, use listen 443 ssl; with a certificate and key.

server_name matches the requested host

The browser sends the hostname in the HTTP Host header. Nginx compares it with server_name values and chooses the corresponding server block. A DNS record alone cannot make Nginx select a configuration; the names in DNS and Nginx must match exactly, including spelling and subdomain level.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

proxy_pass chooses the backend port

The upstream URL determines where Nginx connects. These are distinct destinations:

proxy_pass http://127.0.0.1:3000;
proxy_pass http://127.0.0.1:8080;

Use https:// instead of http:// only when the upstream itself speaks TLS. If the backend uses a self-signed certificate or a private certificate authority, configure upstream certificate verification deliberately rather than assuming the public certificate covers that connection.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

HTTP to HTTPS and certificate setup

For production services, terminate TLS at Nginx. A minimal HTTPS block for the first application looks like this:

server {
    listen 443 ssl;
    server_name app1.example.com;

    ssl_certificate     /etc/letsencrypt/live/app1.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app1.example.com/privkey.pem;

    location / {
        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 https;
        proxy_pass http://127.0.0.1:3000;
    }
}

The certificate must cover app1.example.com. For multiple subdomains, use separate certificates, a certificate with the required Subject Alternative Names, or a suitable wildcard certificate. Do not assume a certificate for example.com automatically covers app1.example.com.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Redirect HTTP to HTTPS

Keep a separate port-80 block that redirects clients, then proxy only on 443:

server {
    listen 80;
    server_name app1.example.com;
    return 301 https://$host$request_uri;
}

Repeat the HTTPS block and redirect for app2.example.com, changing the certificate and upstream port as needed. Ensure public port 80 remains reachable if you expect browsers or certificate automation to use an HTTP challenge.

How SNI affects several subdomains on one IP

TLS Server Name Indication (SNI) lets Nginx choose among multiple HTTPS virtual servers sharing one IP address. The client sends the requested hostname during the TLS handshake; Nginx selects a certificate and then uses the matching server_name. A missing name, an incorrect certificate, or a client that does not send SNI can produce the wrong certificate even when the proxy rules are correct.

Forward the headers your application needs

Nginx does not pass every client header unchanged. By default, it changes the proxied Host to $proxy_host and sets Connection to close. Explicit headers preserve information that applications commonly need:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Host $host tells the backend which public hostname the visitor requested.
  • X-Real-IP $remote_addr supplies the address of the immediate client as seen by Nginx.
  • X-Forwarded-For $proxy_add_x_forwarded_for maintains the proxy chain.
  • X-Forwarded-Proto $scheme tells the application whether the original request used HTTP or HTTPS.

Configure the application or framework to trust these headers only from your Nginx proxy. Blindly trusting client-supplied forwarding headers can let a visitor spoof an IP address or protocol. If an application creates http:// links during an HTTPS request, or redirects repeatedly between HTTP and HTTPS, its trusted-proxy and forwarded-protocol settings are usually incomplete.

WebSockets and connection upgrades

Applications that use WebSockets may need explicit upgrade headers in the relevant location:

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

Add these only where the upstream requires protocol upgrades. Ordinary HTTP proxying does not need them.

Understand the trailing-slash rule in proxy_pass

The URI portion of proxy_pass changes the path Nginx sends upstream. With a prefix location, the difference is significant.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Configuration Request Typical upstream path
location / { proxy_pass http://127.0.0.1:3000; } /dashboard /dashboard
location /app/ { proxy_pass http://127.0.0.1:3000/; } /app/dashboard /dashboard
location /app/ { proxy_pass http://127.0.0.1:3000; } /app/dashboard /app/dashboard

When proxy_pass includes a URI, Nginx replaces the part of the normalized request URI that matched the location. Without a URI, it passes the full normalized request URI. Decide which behavior the application expects before adding or removing a trailing slash. Incorrect path rewriting commonly causes missing assets, broken redirects, or routes that work only at the homepage.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate the configuration before going public

  1. Check syntax and referenced files.
    sudo nginx -t

    The command should report that the syntax is okay and the test is successful. Fix every reported error before reloading.

  2. Reload without dropping existing connections.
    sudo systemctl reload nginx

    Use the service manager appropriate to the operating system if it is not systemd.

  3. Test virtual-host selection locally.
    curl -i -H 'Host: app1.example.com' http://127.0.0.1/
    curl -i -H 'Host: app2.example.com' http://127.0.0.1/

    These requests bypass public DNS while still testing the server_name match.

  4. Test each public hostname.
    curl -i http://app1.example.com/
    curl -i https://app1.example.com/
    curl -i https://app2.example.com/

    Inspect status codes, redirect locations, certificate names, and response headers.

  5. Review logs while reproducing a failure.
    sudo tail -f /var/log/nginx/error.log
    sudo tail -f /var/log/nginx/access.log

If your distribution stores logs elsewhere, use the paths configured in the Nginx configuration. A reload applies new configuration; a full restart is usually unnecessary and can interrupt active connections.

Troubleshooting by symptom

DNS resolves to the wrong address

Run dig for A and AAAA records and compare every returned address with the Nginx host. Remove stale records or correct the authoritative zone. If only some networks fail, check whether an incorrect AAAA record is sending IPv6 clients to a host that is not configured.

502 Bad Gateway

A 502 generally means Nginx could not obtain a valid response from the configured upstream. Check that:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • The application is running and listening on the exact port in proxy_pass.
  • The address is correct; 127.0.0.1 refers to the Nginx machine itself.
  • A local firewall, security policy, container network, or private-network rule allows the connection.
  • The upstream protocol matches reality; do not proxy with HTTPS to a plain HTTP port.
  • The error log does not report connection refusal, timeout, or an invalid upstream response.

The wrong application or default page appears

Check the request’s hostname, spelling, and port. Confirm that the intended block contains an exact server_name and that no earlier default server is catching unmatched traffic. Test with a Host header locally to isolate Nginx matching from DNS.

Certificate warning or wrong certificate

Verify that the HTTPS block listens on 443, the certificate files exist and are readable by Nginx, and the certificate includes the exact hostname. Check for duplicate HTTPS blocks and confirm that SNI selects the intended server_name.

Redirect loop or insecure absolute links

Pass X-Forwarded-Proto and configure the application to trust Nginx. If TLS is terminated at Nginx but the backend believes every request is HTTP, it may redirect an already secure request indefinitely or generate insecure URLs.

Static files or nested routes return 404

Inspect whether the trailing slash in proxy_pass is rewriting the path. Compare the requested URI with the path the application expects, then choose the URI-inclusive or URI-less form deliberately.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Only external requests fail

Confirm that the host or cloud firewall allows public TCP 80 and 443. Backend ports do not need to be publicly exposed in the standard reverse-proxy design; allowing them broadly increases attack surface. If Nginx and the application are on separate hosts, allow the backend port only from Nginx’s private address or network.

Firewall and exposure decisions

For two applications on one Nginx host, the normal firewall policy is:

  • Allow inbound TCP 80 for HTTP and redirects.
  • Allow inbound TCP 443 for HTTPS.
  • Keep ports such as 3000 and 8080 bound to loopback or a private interface.
  • Allow private backend traffic only between Nginx and the application host when they are separate.

Exposing a backend port directly may be necessary for a special protocol or independent client, but it is not required merely because the application listens on that port. If you do expose one, document its authentication, TLS, rate limits, and firewall scope separately from the Nginx proxy.

Choose the right routing architecture

Architecture Public ports Backend ports Certificate handling When it fits
One Nginx host, subdomain per app 80/443 on one IP Private ports such as 3000 and 8080 Nginx terminates TLS per hostname Several web apps on one server
Separate public IP per app 80/443 on multiple IPs Can remain private Each endpoint can terminate its own TLS Isolation or independent infrastructure is more important than shared proxying
Path-based proxying 80/443 on one IP Private ports Certificate covers the shared hostname Applications are designed to run below prefixes such as /app/
Direct nonstandard public ports Application ports exposed to clients Publicly reachable Each protocol and port needs its own exposure plan Special cases where clients must address a port directly

Subdomain-based routing is usually simpler than path-based routing because applications can operate at the root path and do not require prefix-aware asset and redirect configuration. Path-based routing can reduce the number of hostnames, but it makes URI rewriting and application base URLs a central concern.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Operational checklist

  • Each subdomain’s A and, where applicable, AAAA or CNAME record resolves to the Nginx endpoint.
  • The application is listening on the exact private address and port used by proxy_pass.
  • Every hostname has an exact server_name in the intended HTTP and HTTPS blocks.
  • Nginx listens publicly on 80 and 443, with firewall rules matching that design.
  • Certificates cover every hostname and private keys are readable only by the required service accounts.
  • Host, client-IP, forwarding, and protocol headers match the application’s trusted-proxy configuration.
  • The URI form of proxy_pass matches the application’s expected path.
  • nginx -t succeeds before every reload, and logs are monitored after deployment.

Bottom line

Point both subdomains at the Nginx server in DNS, then let separate Nginx server blocks map each hostname to its backend port. DNS handles names, server_name selects the virtual host, listen exposes the public protocol, and proxy_pass chooses the application port. Terminate HTTPS at Nginx, keep backend ports private where possible, and validate DNS, listeners, headers, URI rewriting, certificates, and logs in that order.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

DevOpsDNSHTTPSNGINXreverse proxySubdomainsweb server

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.