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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Put a whole-site HTTP-to-HTTPS redirect in a port 80 Nginx server block, and serve the destination from a separate TLS-enabled port 443 block. After the certificate is installed, validate the configuration with sudo nginx -t, reload Nginx, and check the Location header with curl -I. The same pattern handles canonical hostnames and individual legacy URLs without losing paths or query strings.

What an Nginx redirect does

An Nginx redirect tells the client to request a different URL. Nginx returns an HTTP status such as 301, 302, or 307 and places the destination in the Location response header. The browser, crawler, API client, or command-line tool then makes a new request.

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

For a normal Linux VPS, the clean architecture is:

  • A port 80 block receives plain HTTP and redirects it.
  • A port 443 block completes TLS and serves the application or performs a hostname redirect.
  • Specific legacy paths are handled with exact location rules before broader application routing.

HTTPS redirection cannot work until port 443 has a working certificate and private key. A browser completes the TLS handshake before it can receive an HTTPS response, so a certificate error prevents the redirect from being delivered.

Prerequisites on the VPS

Point DNS to the server

Create or verify the domain’s A record and, if you use IPv6, its AAAA record. They must resolve to the VPS address. Test from a workstation with your normal DNS tools before changing Nginx; a redirect rule cannot compensate for a hostname that reaches another server.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.

Allow both web ports

Permit TCP ports 80 and 443 in the VPS firewall and any cloud security group. Port 80 is needed to receive the initial HTTP request and to support certificate issuance methods that use HTTP. Port 443 is required for the final HTTPS request.

Confirm Nginx and administrative access

You need a working Nginx installation, shell access with sudo, and a site configuration location. Ubuntu commonly stores per-site files in /etc/nginx/sites-available/ and enables them through /etc/nginx/sites-enabled/. Keep a known-good configuration or console access available in case a syntax error prevents a reload.

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.

Prepare a certificate plan

Obtain a certificate before sending users to HTTPS. The certificate must include every hostname that will accept an HTTPS connection, such as both the apex name and its www variant. Ubuntu documents Certbot as its recommended ACME client and provides an Nginx plugin that can update a matching server block.

Choose return or rewrite

Use return for a fixed destination, scheme change, or canonical-host decision. It is easy to read, works in both server and location contexts, and avoids unnecessary regular-expression processing.

Use rewrite when a regular expression must transform many related paths. The rewrite module supports processing flags: last stops the current rewrite phase and starts a new location search, while break stops rewrite processing in the current context. A poorly scoped expression can create a cycle or send an unintended path to the application.

Need Preferred directive Example outcome
All HTTP requests to HTTPS return return 301 https://$host$request_uri;
One exact old URL Exact location plus return location = /old-page
A family of URLs with a pattern rewrite ^/old-section/(.*)$
Testing or a temporary migration return 302 or return 307 Temporary response with a Location header
Permanent destination return 301 or a permanent rewrite Use only after the target is stable

A 301 is permanent and can be cached by clients and search engines. Use 302 or 307 while testing. A 307 preserves the request method, which matters for non-GET requests; do not test a POST migration with a redirect that changes the method unexpectedly.

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.
Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Set up a whole-site HTTP-to-HTTPS redirect

1. Create the port 80 redirect block

Create or edit the site file under /etc/nginx/sites-available/. The following block redirects both the apex and www names while preserving the host, path, and query string:

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

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

$request_uri contains the original path and query string. Thus, a request for http://example.com/old/path?x=1 receives a destination ending in /old/path?x=1. $host keeps the hostname that the client requested, normalized by Nginx.

If one hostname is canonical, use a fixed destination instead of preserving both names:

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

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

This deliberately consolidates both HTTP names on https://example.com. Do not use the preserving form when your SEO or application policy requires one hostname; it would leave both HTTPS hosts active.

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

2. Enable the site

Use the distribution’s normal sites-enabled mechanism. On an Ubuntu-style layout, that normally means creating a link from the file in /etc/nginx/sites-available/ into /etc/nginx/sites-enabled/, while ensuring the link name does not conflict with another site. If the default site captures requests for an unmatched hostname, disable it or give your site a matching server_name.

3. Configure the HTTPS server block

The destination must listen on 443 with TLS enabled and reference the certificate files:

Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.
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;
}

The application directives will differ for a static site, PHP application, or reverse proxy, but the TLS requirements remain: the listener includes ssl, ssl_certificate points to the certificate chain, and ssl_certificate_key points to the private key. Restrict private-key permissions while allowing the Nginx master process to read the key. A path typo or unreadable key causes configuration validation to fail.

4. Obtain the certificate with Certbot

Ubuntu’s documented Nginx example is:

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

The Nginx plugin finds server blocks matching the requested domains, adds the TLS directives, and reloads Nginx. Review the resulting file afterward. The port 80 block should remain redirect-only, while the port 443 block should serve the application or perform the intended canonical-host redirect. Automated edits do not replace checking which block answers each hostname.

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

5. Validate before reloading

  1. Run sudo nginx -t. Do not reload if the test reports a syntax error, duplicate listener, invalid certificate path, missing semicolon, or permission problem.
  2. After a successful test, run sudo systemctl reload nginx. A reload applies the configuration without stopping existing connections.
  3. Check an HTTP request and an HTTPS request, including a representative path and query string:
    curl -I http://example.com/old/path?x=1
    curl -I https://example.com/old/path?x=1
  4. Confirm that the first response is a 301 with a Location header pointing to the intended HTTPS URL. The second request should return the application response, not another redirect, unless a separate canonical-host rule is intentional.

Nginx’s main configuration is usually /etc/nginx/nginx.conf. The principal diagnostic files are /var/log/nginx/access.log and /var/log/nginx/error.log. The access log shows which host and URI reached Nginx; the error log often identifies a failed include, certificate, permission, or rewrite operation.

Canonicalize www and the apex domain

Choose one public hostname and make every combination of scheme and host converge on it. For an apex canonical name, configure the alternate host on both ports:

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;
}

The certificate must cover www.example.com even though that hostname immediately redirects. TLS negotiation happens before Nginx can issue the redirect. If you prefer www as canonical, reverse the hostnames in the two redirect blocks and the serving block.

Keep the HTTP and HTTPS alternate-host blocks separate. A request to https://www.example.com cannot be handled by a port 80 rule, and placing an HTTP-to-HTTPS rule inside the TLS block can create a loop or prevent the intended host consolidation.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Redirect one old URL to a new URL

Exact path

For one known path, use an exact-match location. The leading equals sign prevents a broader prefix rule from taking precedence:

location = /old-page {
    return 301 /new-page;
}

A relative destination keeps the current scheme and host. If the old and new URLs use different hosts or schemes, provide the complete destination instead. Nginx will retain the original query string when the replacement does not define a new one; test the exact behavior with curl -I before making the redirect permanent.

Path family with a regular expression

For a predictable group of paths, a rewrite can capture the changing portion:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
rewrite ^/old-section/(.*)$ /new-section/$1 permanent;

This maps, for example, /old-section/item-a to /new-section/item-a. Keep the expression narrow enough that it cannot match the destination itself or unrelated application routes. The permanent flag produces a 301. During testing, use a temporary redirect form where appropriate, then switch only after the mapping is stable.

Understand last and break

When a rewrite changes an internal URI, last starts a fresh location search, allowing another location block to serve the new URI. break stops rewrite processing in the current context and continues there. Choosing the wrong flag can bypass an intended handler or repeatedly re-enter a rule. Nginx limits internal redirects, but reaching that limit is a symptom of a rewrite cycle, not a fix.

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

Use temporary redirects while testing

Use a 302 or 307 while a migration is being verified, while a destination is under construction, or while traffic is being routed temporarily. Nginx’s return directive supports 301, 302, 303, and 307. The rewrite module can issue 301 or 302 redirects.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
server {
    listen 80;
    server_name example.com;

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

Test from a clean client and with curl -I, because browsers and intermediaries may cache a 301. Change to 301 only when the destination, hostname policy, and path mapping are final.

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

Diagnose common redirect failures

“Too many redirects”

  • Make sure the HTTP-to-HTTPS rule exists only in the port 80 block. The TLS block should serve content or intentionally redirect a different hostname.
  • If a proxy or load balancer terminates TLS before forwarding to Nginx, ensure the upstream request carries the original external scheme correctly. Otherwise Nginx may see every request as HTTP and redirect an already-secure browser request repeatedly.
  • Check whether an HTTPS canonical-host rule points back to the hostname that initiated it. Compare every Location value with the next request’s host and scheme.
  • Use curl -I repeatedly and record each hop; the first response that changes unexpectedly identifies the block to inspect.

Wrong host or a lost path

Use $host$request_uri when both requested hostnames should remain valid, or use a fixed canonical hostname followed by $request_uri when consolidation is intentional. Do not replace $request_uri with only a slash unless discarding the original path is the desired behavior. Include a query string in tests because tracking and application parameters often expose an incorrect replacement.

Certificate error before the redirect

Install a certificate containing every hostname that accepts HTTPS, including an alternate host that will immediately redirect. The browser cannot receive the redirect until the TLS handshake succeeds. Verify the certificate and key paths in the 443 block and rerun sudo nginx -t.

Nginx refuses to reload

Run sudo nginx -t and read the exact file and line in the error. Frequent causes are a missing semicolon, duplicate listen definition, invalid include, inaccessible private key, and a certificate file that does not exist. Correct the configuration, test again, and only then run sudo systemctl reload nginx.

The wrong site answers

Nginx selects a server block using the listener and requested server_name. Check that the intended file is enabled, that the hostname is spelled identically in DNS and configuration, and that an enabled default site is not catching unmatched requests. Inspect the access log to see the received host and request, then compare the active configuration with the block you edited.

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

A rewrite loops or changes unrelated URLs

Review the regular expression, replacement, and processing flag together. Ensure the destination does not satisfy the same expression, and avoid broad expressions such as a catch-all that also matches the new path. Use an exact location and return for single URLs. If a rewrite relies on a second location, use last deliberately; if it should remain in the current context, use break.

Operational checklist

  • DNS A and AAAA records resolve to the VPS.
  • TCP 80 and 443 are allowed through the VPS firewall and security group.
  • The port 80 block contains only the intended HTTP redirect.
  • The port 443 block has listen 443 ssl, a certificate, and a readable private key.
  • The certificate covers every hostname that can receive HTTPS.
  • The canonical-host decision is explicit: preserve the host with $host or force one name.
  • Exact legacy paths use exact locations; regex rewrites are narrow and tested.
  • sudo nginx -t succeeds before every reload.
  • curl -I confirms status codes, Location headers, paths, and query strings.
  • Access and error logs are checked when the observed response differs from the configuration.
  • 301 responses are used only after the destination is stable.

With this separation of responsibilities, Nginx can redirect plain HTTP, consolidate hostnames, and map retired URLs without mixing TLS setup with application routing. The essential safety rule is to validate the configuration and inspect the actual response chain before making a permanent redirect visible to all clients.

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.