Choose one canonical origin—https://www.example.com—and send every other scheme and hostname directly to it. On Nginx, use separate port-based server blocks with return 301; on Apache, use a dedicated port-80 virtual host with Redirect permanent. Both approaches preserve the requested path and query string when configured correctly and avoid unnecessary redirect chains.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
The examples below replace example.com with your domain. Your TLS certificate must cover www.example.com, and the canonical site must be configured on the HTTPS virtual host.
As an Amazon Associate I earn from qualifying purchases.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteWhat the canonical redirect should do
A site should publish one origin and treat every other origin as an alternate. In this guide the canonical origin is https://www.example.com. That means all four common variants must be handled deliberately:
| Incoming URL | Expected result |
|---|---|
http://example.com/path?x=1 |
One redirect to https://www.example.com/path?x=1 |
http://www.example.com/path?x=1 |
One redirect to https://www.example.com/path?x=1 |
https://example.com/path?x=1 |
One redirect to https://www.example.com/path?x=1 |
https://www.example.com/path?x=1 |
Serve the requested content without a redirect |
The path and query must remain intact. A request for /games/arcade?sort=latest should arrive at the same path and query on the canonical host, not at the homepage or at a URL with its parameters removed.
#1 Best Overall
- 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.
Redirecting each alternate directly to the final origin matters. A two-step sequence such as HTTP to HTTPS followed by bare host to www adds latency, complicates caches, and can break clients that limit redirects.
Before changing the server
Confirm DNS and certificate coverage
- Make sure both the bare name and
wwwresolve to the infrastructure receiving the requests you intend to redirect. - Install a certificate valid for
www.example.comon the TLS virtual host. A redirect cannot help a client that fails certificate validation before receiving an HTTP response. - Identify where TLS terminates. If a CDN, load balancer, or reverse proxy handles HTTPS before Nginx or Apache, test the complete path and ensure the origin is not applying a conflicting scheme rule.
Choose the canonical spelling once
Replace every occurrence of example.com in the examples with the actual domain. Do not mix a bare canonical host in one rule with a www canonical host in another. The redirect target, certificate name, application settings, and any proxy-level rule must agree.
Free tools Windows power users keep installed
One-click scans. No signup required.
Nginx configuration
Nginx’s documented canonical-host pattern is a separate server for the non-canonical name. Put redirects in their own server blocks rather than trying to rewrite the request inside the content-serving block. The return directive is valid in server context, and $request_uri carries the original URI, including its path and query string.
Minimal two-host setup
# Redirect the bare host on HTTP to canonical HTTPS www
server {
listen 80;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
# Redirect HTTP requests for www to HTTPS www
server {
listen 80;
server_name www.example.com;
return 301 https://www.example.com$request_uri;
}
# Canonical HTTPS site
server {
listen 443 ssl;
server_name www.example.com;
# ssl_certificate ...;
# ssl_certificate_key ...;
# application locations ...
}
The first block handles http://example.com. The second handles http://www.example.com. A request arriving over HTTPS for the bare host must also be redirected, so the TLS configuration must account for that name rather than relying only on port 80.
Redirecting the bare HTTPS host
If the bare hostname is reachable on port 443, it needs a TLS server block with a certificate valid for that name and a redirect to the canonical host. Without a certificate that covers the bare name, a browser can stop with a certificate warning before Nginx can issue the redirect. A typical arrangement is:
server {
listen 443 ssl;
server_name example.com;
# ssl_certificate must cover example.com
# ssl_certificate_key ...
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl;
server_name www.example.com;
# ssl_certificate must cover www.example.com
# ssl_certificate_key ...
# application locations ...
}
Whether one certificate contains both names or separate certificates are used is an administrative choice; the important requirement is that every HTTPS hostname clients can reach has a valid certificate before the redirect is attempted.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Why $request_uri is important
$request_uri contains the original URI as received by Nginx. Appending it to the absolute target keeps both the path and the query string:
http://example.com/levels/3?mode=hard
becomes:
https://www.example.com/levels/3?mode=hard
Do not replace it with a bare slash when you intend to preserve deep links. A target such as https://www.example.com/ discards the requested path, while a separately constructed variable can accidentally omit or duplicate query parameters.
Handling unexpected hostnames safely
Nginx may receive a request whose Host header is not one of your configured names. If you need to catch those requests, add a deliberate default server that returns a controlled response or a known redirect after considering host-header safety. Do not build a redirect by blindly reflecting an untrusted Host header; that can turn your server into an open redirect and can produce misleading links.
Rank #2
- 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
Validate and reload Nginx
- Place the blocks in the active Nginx configuration and confirm that no other server block claims the same names with higher precedence.
- Run
nginx -tand correct every syntax or certificate-path error before reloading. - Reload Nginx using your platform’s service manager only after the configuration test succeeds.
- Test both HTTP and HTTPS variants from a client that can reach the public endpoint, especially if a proxy or CDN sits in front of Nginx.
Apache virtual-host configuration
With access to the main Apache configuration, the preferred HTTP-to-HTTPS solution is a dedicated port-80 virtual host containing Redirect permanent. Apache’s documentation describes this as preferable to using mod_rewrite for a straightforward host or scheme redirect.
Dedicated HTTP and HTTPS virtual hosts
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
Redirect permanent / https://www.example.com/
</VirtualHost>
<VirtualHost *:443>
ServerName www.example.com
SSLEngine on
# SSLCertificateFile ...
# SSLCertificateKeyFile ...
DocumentRoot /var/www/example
</VirtualHost>
The port-80 virtual host catches both names and sends them to the same HTTPS www origin. Apache’s Redirect permanent / mapping retains the path below the slash when constructing the destination, so a request for /news/item-7 is sent to https://www.example.com/news/item-7. The query string should be checked in your deployment, particularly when another proxy or rewrite layer is present.
The TLS virtual host is where Apache serves the application. Configure its certificate, key, document root, and application directives there. If HTTPS requests for the bare hostname are accepted, provide a TLS virtual host for that name as well and redirect it to https://www.example.com/; otherwise the certificate negotiation can fail before Apache issues an HTTP redirect.
Why a virtual-host redirect is preferred
A port-80 virtual host separates the redirect from application processing. Apache can answer the request before loading the site, and the rule applies consistently to every path. This is simpler to reason about than embedding a global rewrite in application directories and avoids requiring rewrite conditions for a case that Redirect already handles.
Check and reload Apache
- Confirm that the SSL and rewrite modules required by your chosen configuration are enabled. The
Redirectdirective itself belongs to Apache’s alias module. - Run the appropriate configuration check, commonly
apachectl configtest, and fix reported errors. - Reload Apache after the test passes. A reload applies the new virtual-host map without requiring a full machine restart on typical installations.
- Verify which virtual host answers each name, because an earlier or default virtual host can capture a request if the names are not declared as expected.
Apache .htaccess fallback
Some shared hosting plans allow directory-level .htaccess edits but do not permit virtual-host changes. In that case, use mod_rewrite as a fallback. The file must be in a context where overrides are enabled, and mod_rewrite must be loaded.
RewriteEngine On
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]
%{HTTPS} is on for an SSL/TLS connection. The two conditions are joined with [OR], so the rule runs when the request is not HTTPS or when the host is not the canonical www name. Once it runs, the fully qualified substitution issues an external redirect.
The R=301 flag makes the redirect permanent. The L flag tells Apache to stop processing the current rewrite set after sending it. Apache specifically advises pairing [R] with [L]; using [R] alone can pass the rewritten request to later rules and create surprising results.
Use the actual canonical hostname in the condition and target. If your site has additional hostnames, decide explicitly whether they should redirect, return an error, or remain outside this rule. Do not broaden the condition merely to make a test pass.
Preserving paths and query strings
Nginx
Use $request_uri directly after the canonical origin:
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallRank #3
- 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)
return 301 https://www.example.com$request_uri;
This keeps a request such as /search?q=controller together with its query. It also avoids writing separate rules for every application route.
Apache
The virtual-host Redirect permanent / https://www.example.com/ maps the original path beneath the target slash. The .htaccess example uses %{REQUEST_URI} explicitly, so the original URI is present in the substitution. Confirm the resulting Location header in your own stack because front-end proxies and application rewrites can alter what Apache receives or returns.
Testing without creating a redirect chain
Test each input independently. A header-only request shows the status and destination without downloading the page:
curl -I http://example.com/path?x=1
curl -I http://www.example.com/path?x=1
curl -I https://example.com/path?x=1
curl -I https://www.example.com/path?x=1
For the first three commands, expect one redirect response and a Location header pointing directly to https://www.example.com/path?x=1. For the fourth, expect the content-serving response rather than another redirect. To observe every hop, use:
curl -I -L http://example.com/path?x=1
A correct setup reaches the canonical URL after one hop from each alternate input. If the output shows HTTP to HTTPS followed by bare host to www, change the rules so the first response already contains the final origin.
Test with and without a query string, with a nested path, and with a trailing slash where your application distinguishes those URLs. Repeat the tests through the public CDN or load balancer, not only against an internal origin address.
Choosing the redirect status
Use status 301 when the canonical URL is intended to be permanent. Browsers, crawlers, and intermediary caches can retain permanent redirects, so confirm the hostname and scheme before deploying a broad rule. During a temporary migration, a non-permanent response may be safer while you verify behavior, but the final configuration in these examples is permanent.
HTTP clients do not all handle methods identically after a redirect. For APIs or other requests where preserving the original method and body is essential, evaluate 307 or 308 and test the actual clients before publishing a permanent rule. The correct status depends on the application protocol; a browser-oriented page redirect and a write-oriented API request have different failure consequences.
Recommended Free Tools
Troubleshooting common failures
Redirect loop
A loop usually means the proxy and origin disagree about whether the request is secure, or the canonical HTTPS virtual host is itself redirecting. Inspect every hop with curl -I -L, identify which component emits each Location, and ensure only the edge that knows the real client scheme applies the HTTP-to-HTTPS decision.
Rank #4
- 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
Certificate warning before redirect
The client validates TLS before it can read an HTTP response. Install a certificate covering the hostname used in the HTTPS request, including the bare name if you intend to redirect HTTPS bare traffic. A valid certificate only for www cannot safely receive https://example.com connections.
Path or query disappears
Check that Nginx uses $request_uri and that Apache’s target includes the trailing slash in the Redirect permanent mapping or uses %{REQUEST_URI} in the rewrite fallback. Then inspect whether a CDN or application rule replaces the Location header after the web server generates it.
Wrong virtual host answers
If one name serves the wrong site, inspect the active server and virtual-host ordering. Confirm that server_name values in Nginx and ServerName/ServerAlias values in Apache exactly match the request host. Remove duplicate declarations that make the selected block ambiguous.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Redirect works internally but not publicly
Compare direct-origin tests with tests through the public DNS name. A load balancer may terminate TLS, rewrite the host, or cache an older response. Apply the canonical policy at the layer that receives the client request, and make the origin’s behavior compatible with that policy rather than adding a second, conflicting redirect.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Operational choices that affect the rule
Where to enforce the canonical origin
Choose the first component that sees the client-facing scheme and host. If a CDN terminates TLS, it can issue the redirect before contacting the origin; if Nginx or Apache terminates TLS directly, configure the rule there. Do not let the CDN redirect to HTTPS while the origin independently redirects the host, because that commonly creates two hops. Whichever layer is authoritative must forward a consistent host and scheme to the next layer.
Certificate strategy for both names
Every HTTPS request requires successful certificate negotiation before an HTTP redirect exists. A certificate containing both example.com and www.example.com is one option; separate certificates on separate TLS virtual hosts are another. The choice does not change the redirect target, but each reachable name must match the certificate selected by SNI and the virtual-host configuration.
Permanent redirects and rollback
Because browsers and intermediary caches may retain a 301, verify all four host-and-scheme combinations before switching production traffic. Keep a tested configuration that can temporarily return a non-permanent status while you diagnose a migration. After changing the canonical spelling, test from a fresh client or clear cached redirects so an old result does not hide a current configuration error.
Methods, bodies, and non-browser clients
A browser navigation normally tolerates a 301, but an API client sending POST, PUT, or another write request may change its method or discard its body depending on its redirect implementation. If method preservation is required, compare 307 and 308 behavior in the actual client libraries and intermediaries. Do not assume that a status suitable for page navigation is safe for a write endpoint.
Host-header handling
List the hostnames you intentionally serve. For everything else, a default server can return a controlled error or a fixed redirect to the known canonical origin. Never concatenate an arbitrary Host value into the Location header. Besides open-redirect risk, that practice can create password-reset or email links pointing to an attacker-controlled domain.
Best Value
- 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.
One-hop verification matrix
| Request | Status | Location or response |
|---|---|---|
http://example.com/a?b=1 |
301 | https://www.example.com/a?b=1 |
http://www.example.com/a?b=1 |
301 | https://www.example.com/a?b=1 |
https://example.com/a?b=1 |
301 | https://www.example.com/a?b=1 |
https://www.example.com/a?b=1 |
200 or application response | No redirect |
Repeat this matrix for a deep path, an empty query, encoded characters, and a trailing-slash variant that your application treats differently. A correct status alone is not enough: compare the complete Location value and confirm that the final request reaches the expected virtual host.
Deployment checklist
- Canonical origin is documented as
https://www.example.com. - DNS for every intended input reaches the redirecting infrastructure.
- Certificates cover every HTTPS hostname that clients can request.
- Nginx uses separate redirect servers and appends
$request_uri, or Apache uses a dedicated port-80 virtual host withRedirect permanent. - The
.htaccessfallback is used only when virtual-host configuration is unavailable, with[R=301,L]. - Unexpected hosts receive a deliberate, safe response rather than a redirect based on an untrusted
Hostheader. - All three non-canonical variants reach the final URL in one hop.
- The canonical HTTPS
wwwrequest serves content without redirecting. - Deep paths, encoded characters, and query strings remain present in the final
Location. - Configuration tests pass before Nginx or Apache is reloaded.
Frequently Asked Questions
How do I force both http://example.com and https://example.com to https://www.example.com?
Create direct redirects for both the bare and www HTTP hosts, plus a TLS virtual host for the bare HTTPS host. Each redirect should target the full canonical origin, not an intermediate HTTPS bare URL.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
How do I preserve the path and query string?
On Nginx append $request_uri to the absolute target. In Apache, use Redirect permanent / https://www.example.com/ or include %{REQUEST_URI} in the .htaccess substitution, then verify the resulting Location header.
Why does https://example.com show a certificate warning instead of redirecting?
TLS certificate validation happens before Apache or Nginx can send an HTTP response. Install a certificate valid for the bare hostname if that HTTPS endpoint is reachable and should redirect.
Should I use .htaccess or a virtual host in Apache?
Use a dedicated port-80 virtual host with Redirect permanent when you control the main configuration. Use the .htaccess rewrite only when the hosting environment does not allow virtual-host edits.
Why am I seeing two redirects?
One layer is probably redirecting HTTP to HTTPS while another changes the bare host to www. Configure every alternate variant to point directly to https://www.example.com, and test through the public proxy or CDN as well as the origin.
Can I reflect the incoming Host header in an Nginx redirect?
No. Reflect only explicitly approved hostnames. An untrusted Host value can create an open redirect or generate links to an attacker-controlled domain.
Is 301 appropriate for an API request?
Use 301 for a permanent browser-oriented canonical URL after testing. For requests whose method and body must remain unchanged, evaluate 307 or 308 with the actual API clients and proxies.
How can I test every redirect hop?
Use curl -I for each of the four URL variants and curl -I -L to follow the chain. The three non-canonical inputs should reach the final HTTPS www URL in one hop.
The Bottom Line
Pick one canonical origin, give every reachable HTTPS name a valid certificate, and send each alternate directly to https://www.example.com. Nginx should use separate redirect server blocks with $request_uri; Apache should use a port-80 virtual host with Redirect permanent, reserving .htaccess and [R=301,L] for environments without virtual-host access. Validate all four URL variants through the real CDN, proxy, and origin path before relying on the permanent redirect.
Quick Recap
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.




