Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
FREEDOM251

Freedom251 › Blog › HTTPS

How to Set Up Nginx Redirects on a Linux VPS

By Freedom251 Team · · 9 min read

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

The reliable Nginx design is to separate the redirect from the destination: a port 80 server block sends HTTP requests to HTTPS, while a separate port 443 server block terminates TLS and serves the site. Configure DNS, firewall access, and a certificate first; then test with nginx -t and curl -I before making a redirect permanent.

This guide shows whole-site HTTPS redirects, canonical www or apex-host redirects, one-to-one URL changes, regex migrations, temporary test redirects, and fixes for loops, certificate errors, and unexpected virtual hosts.

As an Amazon Associate I earn from qualifying purchases.

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.

Understand the two-server-block design

An HTTP-to-HTTPS redirect is not the HTTPS site itself. Nginx must first accept the request on TCP port 80, return a redirect response, and then accept the browser’s second request on TCP port 443. The TLS server block must already have a certificate and private key; otherwise the browser cannot complete the HTTPS handshake and will never receive a redirect response.

A minimal whole-site arrangement therefore contains:

#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.
  • A port 80 block with the relevant server_name values and a return 301 (or temporary status while testing).
  • A port 443 block with listen 443 ssl, certificate paths, the site’s root or upstream application, and the same names that the certificate covers.

For a fixed scheme or host change, return is clearer and less error-prone than a regular-expression rewrite. NGINX documents that return is valid in both server and location contexts. Use rewrite when a pattern must transform a family of URIs.

Need Preferred directive or status Why
HTTP to HTTPS or one canonical hostname return Direct, readable, and does not require a regex.
One exact old URL Exact location plus return Prevents similar paths from being caught accidentally.
Many paths that share a pattern rewrite Regex captures can build the destination path.
Stable, permanent move 301 Signals a permanent redirect; clients and search engines may cache it.
Testing or short-lived routing 302 or 307 Lets you change the destination without committing a permanent cacheable move.

Prepare the VPS before editing Nginx

Point DNS at the server

Make the domain’s A record (and AAAA record if you use IPv6) resolve to the VPS. Test from a workstation with your normal DNS tools or by requesting the domain itself. If the name still points to an old host, a correct Nginx file will appear not to work because the request is not reaching this machine.

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

Allow both web ports

Permit inbound TCP 80 and 443 in the VPS firewall and any cloud security group. Port 80 is needed for the initial HTTP redirect and is commonly needed for certificate issuance; port 443 carries the resulting secure connection. Also ensure Nginx is actually listening on the addresses you intend to use. Include an IPv6 listener when the domain has an AAAA record.

Locate the active configuration

On Ubuntu, site definitions are normally stored in /etc/nginx/sites-available/ and enabled through /etc/nginx/sites-enabled/. The main configuration is /etc/nginx/nginx.conf. Confirm that your new file is included by the main configuration and check whether the distribution’s default site could capture an unmatched request. Do not disable a default site blindly if another application depends on it; instead, make sure each hostname and listener maps to the intended block.

Create the HTTP redirect block

Create a site file under /etc/nginx/sites-available/, then enable it using the normal sites-enabled mechanism for your Linux distribution. This block handles both IPv4 and IPv6 and redirects every path while retaining the query string:

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

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

The fixed hostname in this example intentionally consolidates both names on https://example.com. If you want each requested hostname to remain unchanged, use the host supplied by the request:

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

    return 301 https://$host$request_uri;
}

$request_uri carries the original path and query string, so a request such as /old/path?x=1 becomes the equivalent HTTPS URL. Choose one policy deliberately: preserving the host is suitable when both names are valid public sites, while a fixed hostname is appropriate when one name is canonical and the other is only an alias.

NGINX also permits the same return inside location /:

server {
    listen 80;
    server_name example.com;

    location / {
        return 301 https://$server_name$request_uri;
    }
}

A server-level return is usually easier to audit because no location can accidentally bypass it. Do not put the HTTP-to-HTTPS return in the TLS server block; that is a common source of loops.

Configure the HTTPS destination

The redirect target must answer on port 443. A simple static-site block looks like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com www.example.com;

    root /var/www/example;
    index index.html;

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

Replace the root and certificate paths with the paths for your application. The ssl listener parameter and both certificate directives are required for this simplified TLS configuration. The certificate’s names must include every hostname that can receive an HTTPS request. A browser validates TLS before it can process an HTTP response, so a certificate that omits www.example.com cannot be repaired by redirecting that name afterward.

Treat privkey.pem as a secret. Restrict its filesystem permissions and ownership while retaining read access for the Nginx master process. A permissions error will make configuration validation or reload fail; do not solve that by making the key world-readable.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [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

Obtain and install the certificate with Certbot

For Ubuntu, the documented approach is to install Certbot from the snap store, ensure DNS and port access are working, and request both names when both will accept traffic:

sudo certbot --nginx -d example.com -d www.example.com

Certbot’s Nginx plugin finds the server block matching the specified domains, adds the TLS directives in place, and reloads Nginx. Review the resulting files afterward. Keep the port 80 block redirect-only and keep the application, static root, or proxy configuration in the port 443 block. If Certbot cannot find a matching name, correct the server_name, DNS, or enabled-site configuration before trying again.

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

Validate and reload safely

  1. Check the complete configuration and certificate paths:
    sudo nginx -t

    Do not reload if this reports an error. Correct missing semicolons, duplicate listeners, invalid include files, bad paths, or certificate permissions first.

  2. Reload without dropping established connections:
    sudo systemctl reload nginx
  3. Inspect the HTTP response and its destination:
    curl -I http://example.com/old/path?x=1

    The response should contain a 301 status and a Location header pointing to the intended HTTPS URL.

  4. Inspect the secure request separately:
    curl -I https://example.com/old/path?x=1

    This request should return the application response, or a deliberate application-level redirect, rather than sending the browser back to HTTP or repeatedly to the same URL.

  5. Repeat tests for every accepted hostname, the site root, a representative deep path, and a query string. Testing only / can hide a lost path or a host-specific server block.

The principal files for diagnosis are /etc/nginx/nginx.conf, /var/log/nginx/access.log, and /var/log/nginx/error.log. The access log shows which requests and statuses occurred; the error log usually identifies syntax, permission, upstream, or internal-redirect problems.

Redirect an alternate hostname to one canonical host

When the apex domain is canonical and www is only an alias, handle both protocols for the alias. The certificate must cover the alias so that an HTTPS request can complete TLS before Nginx returns the host redirect:

server {
    listen 80;
    listen [::]:80;
    server_name www.example.com;

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

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name www.example.com;

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

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

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com;

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

    root /var/www/example;
    index index.html;
}

If you instead want to preserve whichever hostname was requested, put both names in the serving block and use https://$host$request_uri in the port 80 block. Do not combine contradictory policies, such as redirecting www to the apex on one listener and the apex back to www on another.

Redirect one old URL or a group of URLs

Exact path

For a single known path, use an exact-match location. The equals sign prevents broader prefix matching:

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.
location = /old-page {
    return 301 /new-page;
}

A relative destination keeps the current scheme and host. Use an absolute destination when the move also changes hostname. Query-string handling should be tested explicitly, especially if the old URL has parameters that the new application does not expect.

Regex path family

For a family of paths, the rewrite module can capture part of the old URI:

rewrite ^/old-section/(.*)$ /new-section/$1 permanent;

Use a narrow expression. An overly broad pattern can redirect assets, administrative paths, or the destination itself. The permanent flag issues a permanent redirect. During a migration, use a temporary redirect first and inspect real requests before changing the rule to permanent.

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

Understand last and break

With rewrite processing, last stops the current rewrite sequence and starts a new location search, allowing another location to handle the resulting URI. break stops rewrite processing in the current context and continues there. Choosing the wrong flag can bypass the intended handler or cause repeated internal processing. Nginx limits internal redirects to prevent an infinite cycle; a rewrite that repeatedly recreates its own input will eventually produce an error instead of a useful page.

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

Choose the right redirect status while testing

Status Use it for Operational consequence
301 A destination that is stable and intended to be permanent. Browsers, intermediaries, and search engines may cache the move, making mistakes harder to undo.
302 Temporary testing or short-term routing where a client may revisit the original URL. Signals that the original URL remains in use.
307 Temporary redirects where preserving the original HTTP method matters. Unlike a typical browser-followed GET conversion, the method is preserved.

Nginx’s return directive supports 301, 302, 303, and 307. The rewrite module can issue 301 or 302 redirects. Use 302 or 307 while checking a migration, then change to 301 only after the destination, hostname policy, and application behavior are settled. Clear cached redirects in the browser or test with a new client when verifying a change.

Diagnose redirect loops and other failures

Too many redirects

First confirm that the HTTP redirect exists only in the port 80 block. A TLS block that redirects every HTTPS request back to HTTPS, or an application that redirects HTTPS to HTTP while Nginx redirects HTTP to HTTPS, creates a cycle. If a load balancer or reverse proxy terminates TLS before forwarding to Nginx, the upstream request may appear to be HTTP even though the visitor used HTTPS. Configure the proxy and application to convey and trust the external scheme correctly, and apply the public HTTP-to-HTTPS redirect at the layer that can distinguish the original scheme.

The host or path is wrong

Inspect the exact Location header with curl -I. Use $host$request_uri when the requested host should be retained, or a fixed canonical hostname plus $request_uri when consolidating names. Check a URL containing a query string; a redirect that tests correctly at / may still discard parameters if its destination was written incorrectly.

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

Certificate error before a redirect

The browser performs TLS negotiation before Nginx can send an HTTPS redirect. Install a certificate containing every hostname that accepts HTTPS, including an alternate www name, and verify that the certificate and key paths are readable by Nginx. A host redirect cannot compensate for a certificate-name mismatch.

Nginx refuses to reload

Run sudo nginx -t and read the precise file and line in the error. Typical causes are a missing semicolon, duplicate listen or server_name combination, a nonexistent certificate file, or private-key permissions that prevent the master process from reading it. Fix the reported configuration, run the test again, and only then reload.

The wrong site answers

Nginx selects a server block using the listener and the requested server_name. Check both the port and spelling of every name, confirm the intended file is enabled, and inspect whether the distribution’s default site is catching unmatched requests. Test the apex and alternate host independently because they may select different blocks.

A regex rewrite keeps firing

Log the input and destination paths, then make the pattern more specific. Exclude the destination prefix where necessary and decide whether the next location search requires last or whether processing should remain in the current context with break. Repeated internal redirects indicate that the rule is transforming a URI back into another URI that matches the same rule.

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

Production checklist

  • DNS A and, when used, AAAA records point to this VPS.
  • Inbound TCP 80 and 443 are allowed by the VPS firewall and security group.
  • The port 80 block contains only the intended HTTP redirect behavior.
  • The port 443 block listens with ssl, serves the application, and uses a certificate covering every accepted hostname.
  • The private key is protected but readable by the Nginx master process.
  • Canonical-host policy is consistent for both HTTP and HTTPS.
  • Exact redirects use exact locations; regex rules are narrow and their processing flags are intentional.
  • sudo nginx -t succeeds before every reload.
  • curl -I confirms status, Location, host, path, and query-string behavior for representative URLs.
  • Access and error logs are available for diagnosing unexpected matches or loops.

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.

HTTPSLinux VPSNGINXserver administrationweb servers

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
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.