DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
VGSources
Blog

How to Set Up Nginx Domain Redirects the Right Way

Learn the correct NGINX pattern for domain, www, and HTTP-to-HTTPS redirects, including exact configurations, safe rollout steps, URI preservation, and troubleshooting.
Length13 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The reliable pattern for moving a domain in NGINX is a dedicated redirect-only server block for the old hostname. Return the destination URL with $request_uri so the original path and query string survive:

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

Keep the destination site in its own serving block. This separation makes hostname matching predictable, keeps redirect logic out of the application, and avoids unnecessary regular expressions and conditional if rules.

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.

Why a separate redirect server block is the right design

When a request reaches NGINX, it first chooses a virtual server by listening address and the request’s Host header. The server_name directive defines which hostnames a block handles. A redirect-only block should contain the old hostname and only the directives needed to send the redirect. The new hostname belongs in a separate block that serves the application.

NGINX’s own rewrite-conversion guidance describes defining a separate server for the old name as the correct approach. For an unconditional domain move, a return directive expresses the intent directly: every request handled by that block receives one response and one destination.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Putting the redirect in its own block has practical advantages:

  • The old and new hostnames cannot accidentally share application locations.
  • The redirect does not depend on application code, routing, or framework configuration.
  • There is no regex to maintain for a simple hostname mapping.
  • You can test hostname selection independently from the destination site’s content.
  • Removing or changing the migration is a one-block configuration change.

The basic old-domain-to-new-domain configuration

Use an exact hostname in the old domain’s block and preserve the complete requested URI:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    server_name old.example.com;
    return 301 https://new.example.com$request_uri;
}

A request for http://old.example.com/docs/setup?edition=2 is redirected to https://new.example.com/docs/setup?edition=2. The variable $request_uri contains the original path and query string. It is therefore the key part of a domain migration that must retain deep links, search parameters, language selectors, or other URL data.

Do not replace $request_uri with a bare slash unless every old URL is intentionally being collapsed to the destination homepage. That change discards the original path and query string.

Serve the destination separately

The destination hostname should have its own server block, with normal application locations and, for HTTPS, its TLS settings:

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

    ssl_certificate     /etc/nginx/ssl/new.example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/new.example.com.key;

    # application locations...
}

The certificate must cover new.example.com. Protect the private key while keeping it readable by the NGINX master process, as required by the TLS configuration.

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

Choose the hostname pattern deliberately

Exact names are generally clearest for canonical-domain redirects. NGINX also accepts wildcard and regular-expression names, but broad patterns can capture hosts you did not intend to move. NGINX applies documented matching priorities when selecting a virtual server, so a typo, duplicate name, or unexpected wildcard can send a request to a different block.

Pattern Use when Main risk
Exact name, such as example.com One known hostname must redirect Every intended alias must be listed explicitly
Wildcard, such as *.example.com All matching subdomains deliberately share one destination policy Unrelated subdomains may be captured and redirected
Regular expression A pattern-based host policy is genuinely required More complex matching and harder troubleshooting

List only the old hostname in a migration block. Put the destination hostname in the serving block. If both names are listed in the redirect block, the destination can redirect to itself and create a loop.

Canonical apex and www redirects

For an apex-to-www policy, redirect only the apex name and serve www:

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

server {
    listen 443 ssl;
    server_name www.example.com;
    ssl_certificate     /etc/nginx/ssl/www.example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/www.example.com.key;
    # application locations...
}

The reverse policy is the same design with the names exchanged:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

Decide on one canonical hostname before writing the rule. If both apex and www are intended to serve content, neither should be used as an unconditional redirect target for the other.

HTTP-to-HTTPS redirects

HTTPS enforcement normally starts with a port-80 block that redirects every intended HTTP hostname to the canonical HTTPS hostname:

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://www.example.com$request_uri;
}

The HTTPS endpoint is a separate listen 443 ssl block with ssl_certificate and ssl_certificate_key. A port-80 redirect does not configure TLS by itself; the destination must already have a working certificate and server block.

If an upstream proxy or load balancer is already enforcing HTTPS, make sure NGINX builds the redirect using the scheme the client should receive. A mismatch between proxy behavior and NGINX’s redirect target can produce repeated redirects. Test the complete request path rather than checking only the browser’s final page.

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

return versus rewrite

Use return when every request in the matching server or location goes to one destination that can be assembled from variables such as $request_uri. The directive is valid in both server and location contexts and supports redirect status codes including 301, 302, 303, and 307.

Use rewrite when the URI itself must be transformed conditionally or by a pattern. Regex-based transformations are useful for cases such as changing a legacy path structure, but they introduce pattern matching and control-flow complexity that a straight hostname move does not need.

Requirement Prefer Reason
Every request from one hostname goes to one host while retaining its URI return Short, explicit, and easy to audit
Different source paths need different destinations rewrite Pattern-based URI transformation is required
Temporary test migration return 302 or return 307 Avoids committing browsers and intermediaries to a permanent result
Permanent domain or canonical-host move return 301 Communicates that the change is intended to persist

301, 302, and 307: select the status intentionally

A redirect is an HTTP response. The status code and Location header are the authoritative result, not the page eventually displayed by a browser.

  • 301 Moved Permanently: use for a committed domain or canonical-host migration. Browsers and intermediaries may cache it, which makes mistakes harder to reverse.
  • 302 Found: use while testing or for a temporary change where clients should not treat the destination as permanent.
  • 307 Temporary Redirect: use for a temporary redirect when preserving the original request method is important.

For a cautious rollout, begin with a temporary status on a controlled hostname, verify every route, and change to 301 only after the destination and certificate are correct. Once a 301 has been observed, test with a client that can avoid a previously cached browser result.

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.

Plan the hostname and scheme matrix first

Write down every hostname and scheme that can reach the server before editing NGINX. A typical migration has four public combinations: HTTP apex, HTTPS apex, HTTP www, and HTTPS www. Decide which one is canonical and whether each of the other three should redirect directly to it. A direct redirect from every non-canonical combination avoids chains such as HTTP apex to HTTPS apex to HTTPS www.

Apply the same discipline to legacy subdomains. If old.example.com, www.old.example.com, and an older country-code hostname all need to move, list them explicitly or create clearly scoped blocks. Do not assume a wildcard is harmless: it may include administration, staging, mail, or API hosts that require different treatment.

Also decide what should happen to an unknown Host header. NGINX will select a default server when no name matches. A deliberate default policy makes accidental host capture visible and prevents an unrelated application from becoming the response for arbitrary names.

TLS and SNI details that affect redirects

For an HTTPS request, TLS negotiation happens before NGINX can return an HTTP redirect. Therefore, an HTTPS apex-to-www redirect still needs a certificate valid for the apex hostname on the 443 listener. The certificate cannot cover only the eventual www destination. With multiple HTTPS virtual servers, Server Name Indication helps NGINX select the certificate and block associated with the requested name; a missing or incorrectly ordered configuration can produce the wrong certificate before the redirect is sent.

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

Keep certificate and private-key paths in the intended 443 block, and verify that the private key is protected while readable by the NGINX master process. Test the HTTPS source URL directly, not just the HTTP redirect, because a TLS warning prevents a client from reaching the redirect response at all.

Working through proxies and load balancers

Many deployments terminate TLS at a proxy and send a separate HTTP connection to NGINX. In that design, both layers must agree about which host and scheme the client used. If the proxy already redirects HTTP to HTTPS, duplicating the rule in NGINX can create extra hops. If NGINX sees only the proxy’s internal HTTP scheme and constructs an unsuitable target, clients can bounce between the proxy and origin.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Trace one request through every layer and inspect each response’s status and Location header. Keep one component responsible for each unconditional redirect where possible, and ensure the destination hostname is not included in a source block at either layer.

How to deploy a redirect safely

  1. Back up the active configuration. Save the files that define the current NGINX sites and any included configuration so you can restore the previous state.
  2. Define the old hostname exactly. Add a redirect-only block with the intended listen port, the old server_name, and the selected status code.
  3. Preserve the URI. Use https://destination.example$request_uri unless intentionally changing every path. This keeps both the path and query string.
  4. Verify the destination TLS block. Confirm that the destination hostname appears in the 443 server block and that the certificate names cover it. Keep the private key protected and readable by the NGINX master process.
  5. Test the configuration before reloading. Run nginx -t. Do not reload if the test reports a syntax or include-file error.
  6. Reload using the host’s normal service manager. Use the service-management procedure for the operating system or deployment platform hosting NGINX.
  7. Check representative requests. Test HTTP and HTTPS, apex and www variants, a deep path, a URL with a query string, and an unknown host header.
  8. Inspect the response directly. Check the status code and Location header with a command-line client such as curl -I, rather than relying on a browser’s cached behavior.

Useful verification commands

Replace the hostnames with the names in your configuration:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -I http://old.example.com/docs/setup?edition=2
curl -I https://old.example.com/docs/setup?edition=2
curl -I http://example.com/
curl -I http://www.example.com/
curl -I -H 'Host: unknown.example' http://server-address/

For each expected redirect, confirm the intended 301, 302, or 307 status and a Location value with the same path and query string. The unknown-host test shows which deliberate default-server policy handles unmatched names.

Preserving paths and query strings correctly

$request_uri represents the original URI as received by NGINX, including the path and query string. This makes it appropriate for whole-domain moves. For example:

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

The request /docs/setup?edition=2 becomes https://new.example.com/docs/setup?edition=2. This behavior preserves deep links and campaign or filtering parameters without requiring a separate rule for every path.

If the migration also changes the URL structure, handle that as a distinct mapping problem. A single domain redirect should not silently discard information by targeting only https://new.example.com/. For path-by-path changes, document the source and destination patterns and use rewrite only where a pattern transformation is necessary.

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

Common failure modes and their fixes

Redirect loop

Symptoms: The client reports too many redirects, or repeated responses point between the same hosts and schemes.

Likely causes: The destination hostname is also matched by the redirect block, or an upstream proxy already forces HTTPS while NGINX constructs an incompatible redirect.

Fix: Make the old and destination server_name values mutually intentional. Ensure the destination is served by the 443 block, and trace the request through any proxy so only the layer that should redirect is doing so.

Path or query string disappears

Symptoms: Every old URL lands on the homepage, or parameters such as edition=2 are missing.

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

Cause: The target URL ends at the hostname or slash instead of appending $request_uri.

Fix: Use return 301 https://new.example.com$request_uri; and test a deep URL containing a query string.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

The wrong virtual server responds

Symptoms: The response comes from an unexpected site, certificate, or redirect destination.

Causes: A typo, duplicate server_name, overly broad wildcard, or NGINX’s matching priority selects another block.

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.

Fix: Review every block listening on the address and port, prefer exact names for the migration, remove duplicates, and test each hostname directly. Confirm the request’s Host value and, for HTTPS, the destination certificate’s hostname coverage.

TLS warning after the redirect

Symptoms: HTTP correctly points to HTTPS, but the browser warns that the certificate is invalid or does not match.

Cause: The 443 server block or certificate does not cover the destination hostname, or the request is being selected by an unintended TLS virtual server.

Fix: Configure listen 443 ssl, set the certificate and private-key paths, and use a certificate whose names include the exact destination host. Test the HTTPS URL itself, not only the port-80 response.

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

Unexpected host capture

Symptoms: Requests with an unknown Host header reach a real site or receive an unexpected redirect.

Cause: A default server catches unmatched names.

Fix: Establish a deliberate default policy, then test unknown hosts separately. Do not assume that an unmatched name will fail safely merely because it is absent from your intended redirect block.

Permanent redirect cached too early

Symptoms: After correcting the configuration, some clients still follow the old destination.

Cause: Browsers and intermediaries can cache 301 responses.

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.

Fix: Test with 302 or 307 on a controlled hostname first. When a 301 has already been issued, use fresh clients or cache-clearing procedures during validation and allow for intermediary cache behavior.

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

Rollback and post-change checks

Keep the previous configuration backup until the migration has been verified from several networks and clients. If a redirect is wrong, restore the last known-good block, run nginx -t again, and reload through the normal service manager. A rollback changes future responses, but it cannot instantly erase a 301 cached by a browser or intermediary, so temporary status codes are safer during early tests.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

After deployment, repeat checks for every source hostname, both schemes, a root URL, a deep URL, and a query string. Confirm that the final destination is reached in one hop whenever practical, that the destination returns the expected application response, and that no source hostname is accidentally serving content instead of redirecting.

Reference configurations

Old domain to a new HTTPS domain

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

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

    ssl_certificate     /etc/nginx/ssl/new.example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/new.example.com.key;

    # application locations...
}

HTTP and apex to canonical HTTPS www

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

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate     /etc/nginx/ssl/www.example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/www.example.com.key;
    return 301 https://www.example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name www.example.com;
    ssl_certificate     /etc/nginx/ssl/www.example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/www.example.com.key;
    # application locations...
}

The second 443 block handles an HTTPS request to the non-canonical apex and moves it to the canonical HTTPS www host. Its certificate must still cover the apex name, because TLS negotiation occurs before NGINX can send the redirect.

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

Operational checklist

  • Old and destination hostnames are listed in the intended blocks, not accidentally together.
  • The redirect uses the correct permanent or temporary status.
  • $request_uri is present when paths and queries must survive.
  • The destination has a separate 443 SSL server block when HTTPS is involved.
  • The certificate names cover every HTTPS hostname clients will request.
  • nginx -t succeeds before reload.
  • HTTP, HTTPS, apex, www, deep paths, and query strings have been tested.
  • Unknown Host headers have a deliberate default-server outcome.
  • Redirect chains have been checked for loops and unnecessary hops.
  • A 301 was not committed until the temporary test produced the intended results.

Frequently Asked Questions

How do I redirect an old domain to a new domain in NGINX?

Create a dedicated port-80 server block for the old exact hostname and use return 301 https://new.example.com$request_uri;. Serve the new hostname from a separate block, with its own HTTPS configuration when applicable.

How do I redirect www to non-www, or non-www to www?

Choose one canonical hostname, put only the non-canonical name in a redirect block, and serve the canonical name separately. For example, return 301 https://example.com$request_uri; redirects www.example.com while retaining its path and query string.

How do I force HTTP to HTTPS?

Use a port-80 block listing each HTTP hostname and return the canonical HTTPS URL with $request_uri. Configure a separate listen 443 ssl block with a certificate and private key that cover the HTTPS hostname.

Will NGINX preserve the path and query string?

Yes, when the target ends with $request_uri. A request for /docs/setup?edition=2 becomes the same path and query on the destination host. Omitting the variable sends every request to the same root URL.

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

Should I use return or rewrite for a domain redirect?

Use return for one unconditional destination per hostname. Use rewrite only when paths require conditional or pattern-based transformations; it adds regex and control-flow complexity.

Why does my redirect loop?

Check that the destination hostname is not also matched by the redirect block, and inspect any proxy or load balancer that may already enforce HTTPS. Trace each response’s status and Location header to find the layer repeating the redirect.

Why do I get a certificate warning after an HTTP redirect?

The client must complete TLS before receiving an HTTPS redirect. Ensure the 443 server block and certificate cover the hostname requested in the HTTPS URL, including an apex name that will immediately redirect to www.

How can I test an NGINX redirect without browser cache?

Run nginx -t before reloading, then inspect headers with curl -I. Test both schemes, every hostname, a deep path, a query string, and an unknown Host. Use 302 or 307 on a controlled hostname before committing to 301.

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.

The Bottom Line

For a straightforward NGINX domain move, use an exact, redirect-only server block and return 301 https://destination.example$request_uri;. Keep the destination in its own TLS-serving block, validate with nginx -t, and inspect status codes and Location headers before making the redirect permanent.

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 quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
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.