October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk12 min

How to Fix an Nginx Reverse Proxy Redirecting to the Wrong Domain

Trace the first incorrect Location header, identify whether NGINX or the upstream emitted it, then apply the precise fix for virtual-server selection, forwarded headers, proxy_redirect, absolute redirects or canonical host policy.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Find the first incorrect Location header, then fix the component that created it. If NGINX chose the wrong virtual server, correct the matching server_name and default-server layout. If the application returned a backend hostname, pass the public host and forwarded scheme upstream, then rewrite the response with proxy_redirect when necessary. If NGINX created the absolute URL, review server_name_in_redirect and absolute_redirect. Deliberate www/non-www policy belongs in a separate server block with an explicit return 301.

What a wrong-domain redirect actually tells you

A reverse proxy does not usually invent a redirect at random. A browser follows an HTTP response such as 301, 302, 307 or 308 because the response contains a Location header. That header can come from three places:

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 NGINX server block that accepted the request;
  • the application or another upstream service; or
  • a deliberate canonical-host rule that you configured.

The visible symptom is often the same: a public URL changes to localhost, a container name, a private IP, an unexpected port, or the wrong www/non-www variant. The fix depends on the origin, so changing directives at random can create a loop or hide the real problem.

Use the redirect chain as your boundary. The first response that introduces the wrong hostname identifies the layer that must be changed. A later redirect may simply be following the first one.

#1 Best Overall
Recipe Book to Write in Your Own Recipes, Spiral Blank Cookbook 150 Recipes
  • B5 Recipe Book: This hardcover blank recipe book measures 10''×7.3'', containing 150 blank pages, comes with 1 sheet of DIY category stickers, perfect for writing down your own recipes and organizing them in one place.
  • Practical Layout - 5 pages of conversion charts show you everything you'll ever need to know in the kitchen. The table of contents will help organize your personal favorite recipes. A back pocket is designed for loose items.
  • Easy to Use - This blank cookbook is made of high-quality paper with a beautiful hardcover for long-term use. The sturdy gold double-wire spiral binding makes writing easier and page turning smoother.
  • Make Your Own Recipes - This blank cookbook has up to 150 blank pages for you to write in your own recipes, with plenty of space to record ingredients and instructions. You can write down all the special tips for your family members.
  • Thoughtful Gift - A personalized recipe book makes a thoughtful gift for your children or newlyweds, and a great gift for housewarming, weddings, bridal showers, anniversaries, or any other occasion.

Diagnose the redirect chain before editing NGINX

1. Capture every response and Location header

Run the request against the public URL from a shell that can reach the site:

curl -I -L https://public.example/path

The -I option requests headers, while -L follows redirects. Record each status line and each Location value in order. For a less compressed view, run one hop at a time:

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.
curl -I https://public.example/path
curl -I http://public.example/path
curl -I https://www.public.example/path

Suppose the first response is:

HTTP/2 301
Location: https://www.public.example/path

That is an intentional canonicalization if you configured it. If the first response instead says:

HTTP/1.1 302 Found
Location: http://backend:8080/login

the upstream is exposing its internal address, or NGINX is passing that absolute header through unchanged. If the first response points to an unrelated virtual host, NGINX may have selected the wrong server block.

2. Check the configuration NGINX actually loaded

Inspect the complete loaded configuration, not only the file you recently edited:

nginx -T

Search the output for every server block, all listen directives, each server_name, TLS block, and any return, rewrite, proxy_pass or proxy_redirect directive. An included file or an earlier default block may be handling the request instead of the block you expected.

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.

NGINX first considers the address and port in listen, then compares the request’s Host value with server_name. If no name matches, the default server for that address and port receives the request. Therefore, an omitted alias, a typo, a duplicate name, or a TLS block listening on the wrong address can send traffic to a server that redirects elsewhere.

3. Distinguish the emitting layer

Use this practical test:

  • Wrong host appears in the first response from the public endpoint: inspect virtual-server selection and any NGINX return or rewrite.
  • The first response is correct, but a later response changes to a backend name or port: inspect application URL settings, forwarded headers and proxy_redirect.
  • Only one path, such as login or an administrative callback, is wrong: the application probably constructs an absolute URL for that route.
  • HTTP and HTTPS alternate repeatedly: compare the public scheme with the scheme the upstream believes it received.

Do not clear a browser’s cache yet. A cached permanent redirect can conceal whether your server-side correction worked.

Correct NGINX virtual-server selection

Match the public names explicitly

Create a server block whose listen address and TLS settings match the endpoint clients use, and list every intended public name:

server {
    listen 443 ssl;
    server_name public.example www.public.example;

    ssl_certificate     /etc/nginx/tls/public.example.crt;
    ssl_certificate_key /etc/nginx/tls/public.example.key;

    location / {
        proxy_pass http://app_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Use the exact names that appear in DNS, the certificate and client requests. If the certificate block is in one server and the proxy location is in another, verify that the request is not being terminated by the wrong block first.

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

Understand the default server

For a given address and port, NGINX has a default server. An unmatched Host header is handled there. This is useful for rejecting unknown names, but it can also produce a misleading redirect if the default block sends visitors to another domain.

Make the intended default explicit when appropriate, and give unknown hosts a neutral response rather than a redirect to a real site:

server {
    listen 443 ssl default_server;
    server_name _;
    return 444;
}

Do not add a catch-all block until you have confirmed which block should be the default. On a multi-site machine, changing the default can affect unrelated domains.

Check HTTP and HTTPS independently

Port 80 and port 443 have separate server selection. A correct HTTPS block does not repair an HTTP block that redirects to the wrong host. Test both schemes and inspect the listen lines in nginx -T. Also check IPv4 and IPv6 listeners if DNS publishes both; a request reaching a different listener can appear to ignore your edit.

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

Pass the public host and request context to the upstream

By default, NGINX sends the upstream a Host value based on $proxy_host, the host named by proxy_pass. An application that builds absolute links from that value can therefore redirect a user to the internal upstream hostname.

Set the public host explicitly in the proxy location:

location / {
    proxy_pass http://app_backend;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host $host;
}

What each header communicates

Header Purpose Typical value
Host The hostname the application should use for URL generation and virtual-host logic. public.example
X-Forwarded-Proto The scheme the client used at the public edge. https
X-Forwarded-Host The original public host when the framework reads this header instead of Host. public.example
X-Forwarded-For The client address chain accumulated through proxies. An address list created by $proxy_add_x_forwarded_for

These headers only help if the application trusts the proxy that sets them. Configure the framework’s trusted-proxy or proxy-awareness setting according to its own documentation. If it ignores forwarded headers, it may continue to believe requests are HTTP or addressed to the backend. If it trusts every client, an untrusted caller may be able to spoof host or scheme information. Restrict trust to the proxy path and test the application after changing it.

Preserve a non-standard public port

$host contains the hostname without a port. If users reach the service on a public port other than the scheme’s default, the application may need the original port as well. Pass X-Forwarded-Port when the framework supports it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
proxy_set_header X-Forwarded-Port $server_port;

Whether $server_port represents the desired external port depends on where TLS and port translation occur. Confirm the value with an application log or a temporary diagnostic endpoint; do not assume the backend’s listening port is public.

Rank #2
Pipilo Press Blank Family Cookbook Recipe Binder - 6.5 x 8.2 in Hardcover Spiral Bound - 90 Ruled Pages with Memo Pocket - Write In Your Own Recipes & Meal Planning Notebook
  • Create a Culinary Legacy: The Pipilo Press Blank Family Cookbook Recipe Binder offers a timeless platform for chronicling beloved recipes. With its hardcover and spiral binding, this recipe book to write in your own recipes ensures durability and ease of use for generations
  • Thoughtful Gifting Choice: This book for writing recipes is an ideal present for various occasions, adding a personal touch to celebrations. Its elegant design makes it perfect for moms cookbook DIY projects or anyone passionate about preserving family traditions
  • Durable Design Features: Constructed with a 300gsm cardstock cover and matte lamination, this cookbook you can write in ensures longevity. Its spiral-bound format provides convenient access to pages, making it a practical tool for everyday use
  • Organized Recipe Storage: The included memo pocket offers a space to store handwritten notes or recipe cards, enhancing its functionality. This feature transforms the recipe book for moms into a sentimental family memento
  • Ample Writing Space: Measuring 6.5 x 8.2 inches, this blank spiral family recipe cookbook offers plenty of room for detailed notes. It is perfect for jotting down ingredients, preparation methods, and serving suggestions for a complete culinary record

Rewrite backend Location headers with proxy_redirect

If the upstream sends an absolute redirect such as Location: http://backend:8080/login, setting request headers may not be enough. The application may still emit its own internal URL. NGINX’s proxy_redirect directive rewrites Location and Refresh response headers from a proxied server.

Rewrite an internal origin to the public root

location / {
    proxy_pass http://backend:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_redirect http://backend:8080/ /;
}

A response header such as Location: http://backend:8080/login becomes a relative Location: /login. The browser stays on the public origin and retains its current scheme and host.

Rewrite directly to a known public origin

proxy_redirect http://backend:8080/ https://public.example/;

This produces an absolute public URL. It is useful when clients or a framework require an absolute location, but it hard-codes one canonical host. If the same proxy serves several hostnames, a variable can follow the request host:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
proxy_redirect http://backend:8080/ https://$host/;

Only use host-preserving behavior when accepting multiple public names is intentional. If one name is canonical, redirect aliases in dedicated server blocks instead of allowing arbitrary host values to become canonical URLs.

Match the exact upstream scheme, host and port

The replacement pattern must match what the upstream actually returns. Check whether it uses http or https, a name or an IP address, and a port. A rule for http://backend:8080/ does not match https://backend:8443/. Add narrowly scoped rules for each confirmed origin rather than a broad replacement that could alter unrelated links.

When proxy_redirect is not the real fix

Response rewriting is a containment measure. The durable fix is usually to configure the application with its public base URL and trusted proxy settings. Otherwise, password-reset links, form actions, WebSocket endpoints or API responses may still contain the internal origin even though one redirect is rewritten. Use proxy_redirect when you cannot change the upstream or when a specific legacy response must be translated at the edge.

Fix redirects generated by NGINX itself

server_name_in_redirect

When NGINX generates an absolute redirect, server_name_in_redirect controls whether it uses the primary name from the selected server block or the host supplied in the request. If the primary name is an internal or obsolete hostname, an absolute redirect can expose it. Review the directive at the server or http level and choose behavior that matches your policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    server_name public.example;
    server_name_in_redirect off;
}

With this setting, NGINX can use the request’s host when constructing an absolute redirect. That is appropriate only when the request host has already been validated and you intentionally support it.

absolute_redirect

absolute_redirect controls whether NGINX emits absolute URLs in redirects. Turning it off makes redirects relative, which avoids exposing a server name in the header:

absolute_redirect off;

A relative redirect can be useful behind a proxy chain, but it is not a substitute for a clear canonical-host policy. Check clients and integrations that expect absolute URLs before changing this globally.

Look for return and rewrite directives

Search the loaded configuration for rules such as return 301 https://old.example$request_uri; or a rewrite whose replacement contains an obsolete name. A rule in an included file can run before the proxy location. Remove or update the stale rule, then test the exact path that triggered it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Implement intentional www/non-www canonicalization

If the goal is to send every request to one host, use separate server blocks and an explicit return 301. This is clearer than embedding host switching inside a proxy location.

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

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

    location / {
        proxy_pass http://app_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Add a separate TLS redirect block for the non-canonical HTTPS name when certificates cover it:

server {
    listen 443 ssl;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}

Ensure the certificate presented for the redirecting HTTPS name is valid; otherwise the browser can fail before it receives the redirect. Keep the canonical block free of a rule that redirects back to the alias. A pair of reciprocal rules creates a loop.

Do not use an ad-hoc if inside the proxy location for ordinary host canonicalization. Separate servers make matching, certificates and redirect intent explicit and avoid ordering problems.

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

Common failure patterns and targeted fixes

Symptom Likely source Targeted action
The first response points to another site on the same machine. Wrong server_name, listener or default server. Run nginx -T; correct names and listen blocks; inspect the default server.
Login redirects to localhost, a container name or a private IP. Application builds URLs from the upstream host. Set proxy_set_header Host $host, pass forwarded headers, configure trusted-proxy settings, and add a precise proxy_redirect rule if needed.
The host is right but HTTP and HTTPS alternate. Upstream does not know the public scheme, or both layers enforce opposite policies. Pass X-Forwarded-Proto $scheme; configure application proxy awareness; leave only one deliberate HTTPS policy.
The host is right but an unexpected port appears. Absolute URL generation uses the backend port or loses the external port. Inspect Location; pass a supported X-Forwarded-Port; rewrite the exact upstream origin.
Only one hostname loops between www and non-www. Both server blocks redirect to each other, or the application canonicalizes the opposite name. Choose one canonical name and remove the conflicting rule in the other layer.
Your edit has no effect. Another included file or listener handles the request, or NGINX was not reloaded. Use nginx -T, run nginx -t, reload, then repeat the same curl test.
Command-line tests work but a browser still redirects. A cached 301/308 response or service-worker behavior. Verify headers with curl from a clean client; clear browser cache only after the server chain is correct.

Two complete configuration patterns

Public HTTPS to an HTTP application

This pattern terminates TLS at NGINX while keeping the public origin visible to the application:

upstream app_backend {
    server 127.0.0.1:8080;
}

server {
    listen 443 ssl;
    server_name public.example;

    ssl_certificate     /etc/nginx/tls/public.example.crt;
    ssl_certificate_key /etc/nginx/tls/public.example.key;

    location / {
        proxy_pass http://app_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_redirect http://127.0.0.1:8080/ /;
    }
}

Replace the rewrite source with the exact host and port that the application puts in its Location header. If the application is configured correctly and returns relative locations, remove the unnecessary rewrite rather than keeping a broad rule.

Canonical host with an alias redirect

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

server {
    listen 443 ssl;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}

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

    location / {
        proxy_pass http://app_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Use certificates that cover both HTTPS names. The canonical block should proxy the request; only the alias blocks should redirect.

Validate safely and confirm the final chain

  1. Save the configuration and run nginx -t. Do not reload if syntax validation fails.
  2. Reload NGINX using your operating system’s service method, for example systemctl reload nginx.
  3. Repeat curl -I -L https://public.example/path and compare every Location header with the pre-change capture.
  4. Test an ordinary page, the failing login or callback path, both HTTP and HTTPS, and each supported canonical or alias hostname.
  5. Check the final response status and URL. A deliberate one-hop canonical redirect is different from a chain that alternates hosts or schemes.
  6. After the server-side result is correct, clear cached permanent redirects in affected browsers and retest.

For a stubborn case, temporarily log the request host, forwarded scheme and upstream response headers at the application or proxy boundary. The goal is to prove three values independently: which server block received the request, what headers the upstream saw, and what exact Location it returned.

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

Choose the fix by redirect origin

Redirect origin Hostname source Best first fix Important qualification
NGINX server selection Matched server_name or default server Correct listen, server_name and default arrangement. Check HTTP and HTTPS separately.
NGINX-generated absolute redirect Primary server name or request host Review server_name_in_redirect and absolute_redirect; remove stale return/rewrite rules. Use only a validated host when preserving the request host.
Upstream-generated redirect Backend host, application base URL or inferred scheme Pass Host and forwarded headers; configure trusted-proxy behavior. Application settings remain the durable source of truth.
Upstream absolute header that cannot be changed Internal origin in Location or Refresh Use a precise proxy_redirect rule. Match the exact scheme, host and port.
Intentional canonicalization Policy-defined canonical host Dedicated alias and canonical server blocks with return 301. Prevent reciprocal redirects and cover TLS certificates.

Final checklist

  • Captured the complete chain and identified the first wrong Location.
  • Confirmed the active configuration with nginx -T.
  • Verified the request host matches the intended server block.
  • Set proxy_set_header Host $host when the application needs the public hostname.
  • Passed X-Forwarded-Proto, X-Forwarded-Host and X-Forwarded-For as required by the framework.
  • Configured the application’s trusted-proxy behavior.
  • Used proxy_redirect only for confirmed upstream response origins.
  • Reviewed server_name_in_redirect, absolute_redirect and stale rewrite rules.
  • Placed www/non-www policy in separate server blocks.
  • Ran nginx -t, reloaded, and retested with curl before clearing browser cache.

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.

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

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.