Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon 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
World desk9 min

How to Redirect a Subdomain to a Subfolder in Nginx

A practical Nginx guide to redirecting a subdomain into a subfolder, preserving paths and query strings, choosing between return, rewrite and proxy_pass, and validating HTTPS and DNS.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To send blog.example.com to https://example.com/blog, create a dedicated Nginx server block for the subdomain and return a 301 redirect that appends $request_uri:

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

    return 301 https://example.com/blog$request_uri;
}

This changes the browser’s address, preserves the incoming path and query string, and keeps the rule separate from the destination site’s application routing.

As an Amazon Associate I earn from qualifying purchases.

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 basic subdomain-to-subfolder redirect

A hostname redirect belongs in its own virtual server. Nginx selects that server by the request’s Host header, so matching blog.example.com explicitly prevents the rule from affecting unrelated names handled by the same Nginx instance.

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

    return 301 https://example.com/blog$request_uri;
}

A request for http://blog.example.com/ receives:

HTTP/1.1 301 Moved Permanently
Location: https://example.com/blog/

A request for http://blog.example.com/articles/nginx?format=amp receives a location such as:

#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.
https://example.com/blog/articles/nginx?format=amp

$request_uri is the original request URI, including its path and query string. Appending it after /blog is what carries nested URLs and parameters to the new location. URL fragments, such as #comments, are never sent to the server and therefore cannot be copied by Nginx.

Choose the status code deliberately

Use 301 only when the move is permanent. Browsers, proxies and search systems can cache a permanent redirect, which makes later configuration changes appear ineffective. During a test or staged migration, use 302 first:

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

    return 302 https://example.com/blog$request_uri;
}

Once the destination, links and assets behave correctly, change the response to 301. Nginx also supports 303 and 307 with return. A 307 preserves the request method, while a temporary 302 is commonly used for ordinary browser navigation. Pick the code that matches the client behavior you require, rather than changing codes to work around a cached response.

What the redirect does to a request

This configuration performs a client-side redirect. Nginx sends a 3xx response and a Location header; the browser then makes a new request to example.com/blog. The address bar, cookies sent to the destination, canonical URL and any subsequent redirects are therefore based on the destination host.

The original path is joined directly to the configured subfolder. With the rule above, the mapping is:

  • / becomes /blog/.
  • /news becomes /blog/news.
  • /news/page.html?year=2026 becomes /blog/news/page.html?year=2026.

Decide whether that joining behavior is what the application expects. If every old URL should land on one fixed page, omit $request_uri and return only the target path:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
return 301 https://example.com/blog;

That variant intentionally discards the old path and query string.

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.

Why return is usually the right directive

For a straightforward hostname move, return expresses the outcome directly and can run at the server level. It avoids conditional logic and makes the redirect target easy to audit.

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

    return 301 https://example.com/blog$request_uri;
}

The rewrite directive is useful when you need a pattern-based transformation, but it is more syntax than a simple host redirect requires. An external rewrite can use the redirect flag for a temporary redirect or permanent for a permanent one:

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

    rewrite ^/(.*)$ https://example.com/blog/$1 permanent;
}

Pattern rewrites need careful handling of slashes, escaping and query strings. Prefer return when the entire subdomain follows one destination rule; use rewrite when different paths genuinely need different pattern mappings.

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

Redirect versus internal routing

Do not use an external redirect if the subdomain must remain visible to visitors. An internal rewrite changes the URI Nginx processes without sending a 3xx response, so the browser continues to display blog.example.com. This is appropriate when the subdomain is an alternate public hostname but the same Nginx server should route requests through a different internal path.

External and internal behavior have different consequences:

  • External redirect: the client makes a second request, the address bar changes, and the destination host controls cookies, canonical links and later redirects.
  • Internal rewrite: the client sees no redirect, while Nginx changes the URI used for local processing.

The rewrite module’s redirect and permanent flags produce external 302 and 301 responses respectively. Without those flags, a rewrite remains an internal routing operation.

Keeping the subdomain while proxying to a subfolder

If an upstream application must receive a /blog/ path while visitors stay on blog.example.com, use a location and proxy_pass deliberately:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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
server {
    listen 80;
    server_name blog.example.com;

    location / {
        proxy_pass http://app_backend/blog/;
    }
}

Because this proxy_pass includes a URI (/blog/), Nginx replaces the portion of the request URI that matched location / with /blog/ before forwarding it. A request for /article?id=7 is therefore sent upstream with the /blog/ prefix and the remaining path. If proxy_pass has no URI, Nginx forwards the full request URI instead.

Trailing slashes are significant. Compare location / with proxy_pass http://app_backend/blog/ to the same directive without the trailing slash; they do not produce identical upstream paths. Test the exact combinations your application expects.

Also inspect upstream-generated Location headers. An application may redirect clients to an internal hostname or to a path that omits the required prefix. Such responses can create loops or expose the wrong URL. Verify them with an HTTP client before deploying the proxy arrangement.

DNS and server_name prerequisites

Point the subdomain at the Nginx host

Create an A record for an IPv4 address, an AAAA record for IPv6, or an appropriate CNAME arrangement so blog.example.com reaches this Nginx server. DNS changes must be visible to clients before testing can be meaningful.

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

Match the exact hostname

Include the requested name in server_name:

server_name blog.example.com;

Nginx chooses a virtual server using the request name. If no configured name matches, the request can fall into the listener’s default_server, where a completely different response may be returned. A redirect that works when addressed by IP, or only works from one network, is often testing the wrong virtual server or stale DNS.

Adding HTTPS correctly

For HTTPS, the subdomain needs a certificate that covers blog.example.com and a TLS listener. A common arrangement uses one HTTP block to upgrade to HTTPS and a separate TLS block to perform the host-to-subfolder redirect:

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

    return 301 https://blog.example.com$request_uri;
}

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

    ssl_certificate     /path/to/blog.example.com.crt;
    ssl_certificate_key /path/to/blog.example.com.key;

    return 301 https://example.com/blog$request_uri;
}

The first block sends an HTTP client to the HTTPS version of the same subdomain. The second block then sends the HTTPS request to the destination host. This two-step sequence means the certificate for blog.example.com must be valid before Nginx can issue the second redirect; a browser validates TLS before it accepts the HTTP response.

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.

The destination host also needs HTTPS configured if the redirect target uses https://example.com. Do not assume that a certificate on one hostname covers another unless the certificate’s names explicitly include both.

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.

Configuration procedure

  1. Confirm the intended mapping. Decide whether all old paths should be appended after /blog, whether the query string must survive, and whether the browser should change hosts or remain on the subdomain.
  2. Configure DNS. Point blog.example.com to the Nginx host with the required A, AAAA or CNAME record.
  3. Create the matching server block. Put server_name blog.example.com in a block that listens on the protocol you are testing.
  4. Start with a temporary response. Use return 302 https://example.com/blog$request_uri; while checking paths, parameters, assets and application redirects.
  5. Validate the syntax. Run nginx -t. Do not reload a configuration that fails this test.
  6. Reload Nginx. Apply the validated configuration using your platform’s normal reload operation, avoiding a stop/start that unnecessarily interrupts active connections.
  7. Test the root and a nested URL. Check the bare subdomain, a path containing multiple segments and a URL with a query string.
  8. Inspect the response headers. Confirm the status and exact Location value, then follow the redirect to verify that the destination serves the expected subfolder.
  9. Switch to 301 only after verification. Once the mapping is stable, replace the temporary code with 301 and reload after another successful syntax test.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Testing with curl

Request headers without downloading the response body:

curl -I http://blog.example.com/

Test a nested path and query string:

curl -I 'http://blog.example.com/articles/nginx?format=amp'

For HTTPS, inspect certificate and redirect behavior separately:

curl -I https://blog.example.com/articles/nginx?format=amp

Look for a 301 or 302 status and a Location header containing the expected destination. If you use curl -L to follow redirects, retain at least one run without -L; otherwise the first response can be hidden and a redirect loop becomes harder to diagnose.

Common failures and fixes

The request reaches the wrong site

Check DNS resolution, the exact Host name, the enabled Nginx configuration and whether another block is marked default_server. Testing by IP does not exercise hostname matching and can select a different server block.

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

The path is duplicated or missing

Review the join between /blog and $request_uri. A target ending in /blog plus a request URI beginning with / produces /blog/.... If a fixed destination is intended, remove $request_uri. For proxying, compare the exact trailing slashes on both location and proxy_pass.

The query string disappears

Use $request_uri in the return target. A manually constructed path that omits the original URI will not carry the incoming parameters. Test with a visible parameter such as ?check=1 and inspect the Location header.

A redirect loop occurs

Check every hop, not just the first response. The destination application may redirect back to the subdomain, an HTTP-to-HTTPS rule may point to the wrong host, or a proxied upstream may emit an unsuitable Location header. Follow the chain with a header-only client and correct the first rule that sends the request backward.

The browser appears to ignore a change

A cached 301 can survive configuration edits. Test with a temporary 302 on a fresh URL or a clean client, and inspect the response directly with curl -I. Do not infer the active Nginx configuration from a browser result alone.

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

HTTPS fails before the redirect is returned

Verify that the TLS block listens on port 443, that its server_name matches the requested subdomain and that the certificate covers that name. A browser cannot receive the redirect until the TLS handshake succeeds.

When NGINX Ingress Controller is involved

Kubernetes NGINX Ingress Controller does not use a hand-written server block in the same way as a standalone Nginx installation. URI transformations are configured with the controller’s annotations and the path rules in an Ingress resource.

The controller documentation lists nginx.org/rewrite-target, which supports regex capture groups when path-regex is used, and nginx.org/rewrites for rewrite mappings. These two annotations are mutually exclusive; choose the form supported by the controller version and configuration style running in the cluster.

Before applying an Ingress change, confirm which controller implementation and annotation set is installed. An annotation accepted by one NGINX Ingress product or version may be ignored by another, leaving the request at the original path.

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

Operational checks after the redirect works

  • Open representative destination pages and verify that CSS, JavaScript, images and API calls use the destination host and correct /blog prefix.
  • Check canonical links and generated absolute URLs so search engines and users are not sent back to blog.example.com.
  • Review cookies: cookies scoped only to the old subdomain will not automatically be available to example.com.
  • Inspect application redirects, login callbacks and form actions, especially where the old hostname was embedded in configuration.
  • Retest both HTTP and HTTPS entry points, the bare path and a nested path with a query string after every Nginx reload.

Choosing the right pattern

Requirement Nginx pattern Browser URL
Move the subdomain permanently to the main site’s subfolder return 301 https://example.com/blog$request_uri; Changes to example.com/blog...
Test the move without committing to cacheable permanence return 302 https://example.com/blog$request_uri; Changes temporarily
Keep the subdomain visible while Nginx routes locally Internal rewrite rules Remains on blog.example.com
Keep the subdomain visible while an application receives a prefixed path location with URI-bearing proxy_pass Remains on blog.example.com
Apply the mapping in Kubernetes NGINX Ingress Ingress rewrite annotations and path rules Depends on whether the rule is external or internal

For the specific move from blog.example.com to example.com/blog, the separate server block and a return directive are the least surprising implementation. Use internal routing or proxying only when retaining the subdomain in the browser is an intentional requirement.

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair 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.