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

Use HTTP 302 for a temporary redirect and HTTP 301 for a move that should be treated as permanent. In Apache, use Redirect for a fixed path mapping and mod_rewrite when you need conditions or regular expressions. In Nginx, use return for a fixed destination and rewrite for pattern-based changes. Test the old URL, status code, Location header, path, and query string before deploying a permanent rule.

Choose the redirect status first

A redirect is an HTTP response that tells the client to request another URL. The server sends a status code and a Location header; the browser, crawler, API client, or other user agent then follows that location according to its own rules.

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.
Use case HTTP status Apache Nginx
Temporary test, campaign, maintenance page, or short-lived routing change 302 Redirect temp, omitted Redirect status, or [R=302,L] return 302 or rewrite ... redirect
Permanent URL, domain, or protocol move 301 Redirect permanent or [R=301,L] return 301 or rewrite ... permanent
Temporary method-preserving redirect where the client must not change the request method 307 Use an explicit rewrite status if your application requires it return 307
See-other response, commonly after a form submission 303 Use an explicit rewrite status if appropriate return 303

Apache’s Redirect directive defaults to a temporary 302 when no status is supplied. Apache’s mod_rewrite R flag also defaults to 302. Nginx’s rewrite directive returns 302 with the redirect flag. A 301 is a declaration that the old address has moved permanently, so browsers, crawlers, caches, bookmarks, and integrations may retain or reuse it. Do not use 301 merely to test a rule that you expect to change soon.

Apache: use the simplest directive that fits

Apache can apply redirects in the main server configuration, a virtual host, a directory context, or an .htaccess file, depending on the directive and your hosting permissions. A fixed mapping is easier to audit with mod_alias‘s Redirect. Conditions, regular expressions, header checks, and more involved transformations belong in mod_rewrite.

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

Permanent redirect for one path with Redirect

Put this in the relevant virtual host or server configuration when /old-page should always lead to the new URL:

Redirect permanent "/old-page" "https://www.example.com/new-page"

permanent sends HTTP 301. The source path is matched by Apache and the destination is returned to the client. This form is preferable to a rewrite rule when there is no condition or pattern to evaluate.

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

Temporary redirect for one path

Use temp when the mapping is deliberately short-lived:

Redirect temp "/campaign" "https://www.example.com/campaign-preview"

Leaving out the status also produces a temporary 302:

Redirect "/campaign" "https://www.example.com/campaign-preview"

Keep the temporary rule while you test the destination, then change it to a 301 only after the final URL and behavior are confirmed.

Regex or conditional redirects with mod_rewrite

Enable the rewrite engine and use a regular expression when many old URLs share a structure:

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
RewriteEngine On
RewriteRule "^/old/(.*)$" "https://www.example.com/new/$1" [R=301,L]

The capture group (.*) is inserted at $1. Replace 301 with 302 while testing. Apache documents that an external redirect should almost always use R together with L. Without L, later rules can process the redirect again, creating an invalid URI warning, an unexpected second redirect, or a loop.

In a server or virtual-host context, the pattern commonly includes the leading slash. In per-directory or .htaccess context, Apache removes the directory prefix before matching, so the pattern normally does not start with /:

RewriteEngine On
RewriteRule "^old/(.*)$" "https://www.example.com/new/$1" [R=302,L]

Check the context before copying a pattern. A rule that is correct in a virtual host can fail to match in .htaccess solely because of that slash difference.

Redirect all HTTP traffic to HTTPS

For a straightforward HTTP-to-HTTPS migration, Apache’s server configuration can use a dedicated port-80 virtual host:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent "/" "https://www.example.com/"
</VirtualHost>

The source slash covers every path under that host, and the relative path is retained by Apache when it constructs the redirect. If you need conditions or host-based logic, use mod_rewrite instead.

When only .htaccess is available, Apache documents this pattern:

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.
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule "^(.*)" "https://%{SERVER_NAME}$1" [R=301,L]

On a load-balanced or reverse-proxy deployment, the origin server may see every connection as HTTP even when the visitor used HTTPS. In that design, test a trusted X-Forwarded-Proto value supplied by the controlled proxy rather than relying on %{HTTPS}. Only trust a forwarding header that your proxy overwrites; accepting a client-supplied value can let requests bypass the intended check or create a redirect loop.

Control Apache query strings deliberately

When a rewrite changes the query string, Apache’s flags determine what happens to the original parameters. QSA (query-string append) preserves the old query string and appends it to the new one. QSD (query-string discard) removes the original parameters.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
RewriteEngine On
RewriteRule "^/search$" "/results?source=redirect" [R=302,QSD,L]

That rule sends /search?term=apache to /results?source=redirect, not to a URL that also contains term=apache. Use QSA when retaining the incoming parameters is intentional:

RewriteRule "^/old-search$" "/results?source=old-search" [R=302,QSA,L]

Without an explicit decision, tracking parameters, authentication state, or duplicate keys can be copied to a destination where they are no longer appropriate. Test both a URL with no query string and one with representative parameters.

Nginx: use return for fixed destinations

Nginx places redirects in the matching server or location block. The return directive is the clearest choice when one known request should produce one known destination. Nginx accepts redirect status codes including 301, 302, 303, and 307.

Permanent redirect for one exact path

location = /old-page {
    return 301 https://www.example.com/new-page;
}

The = modifier makes this an exact location match, so /old-page is handled without also matching longer paths such as /old-page/archive. Remove the modifier or use a prefix location when a whole subtree should be redirected.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Temporary redirect

location = /maintenance {
    return 302 https://www.example.com/status;
}

Use 302 for a preview, maintenance endpoint, or experiment that may be removed. If a request method must be preserved during a temporary move, choose 307 instead of assuming every client treats 302 identically.

Regex transformation with rewrite

Use rewrite when the destination is derived from part of the path:

rewrite ^/old/(.*)$ https://www.example.com/new/$1 permanent;

The permanent flag returns 301. Replace it with redirect for 302:

rewrite ^/old/(.*)$ https://www.example.com/new/$1 redirect;

For a rewrite that changes the URI and should trigger a new location search, use last. If restarting location selection would match the same rule again, use break to continue processing in the current location. Choosing the wrong flag is a common source of loops or rules that appear to be ignored.

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.

Canonicalize a host while preserving the complete request URI

Use a separate server block for an old host and return the original request URI:

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

$request_uri contains the path and the original arguments, so a request such as /docs/start?lang=en is redirected to the same path and query string on the new host. Nginx’s conversion guidance recommends this direct server-level return instead of an if-plus-rewrite construction for host canonicalization.

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.

Preserve paths and query strings intentionally

A domain move normally needs to preserve every path, not just the home page. A path migration may instead map one old path to one new path, or transform a family of paths with a captured suffix. Decide which of those behaviors you need before writing the rule.

Goal Apache approach Nginx approach
One old path to one new path Redirect permanent or a single RewriteRule location = ... { return 301 ...; }
Preserve a path suffix Capture it with RewriteRule and reuse $1 Capture it with rewrite and reuse $1
Preserve the original query string while adding parameters Use QSA Use a replacement that retains the arguments and verify the resulting URL
Discard incoming parameters Use QSD Use replacement syntax that suppresses the original arguments, then test the response
Preserve path and arguments during a host move Build the destination from a trusted canonical host and the matched path Use $request_uri in a dedicated old-host server block

Nginx appends original arguments when a rewrite replacement does not introduce a new argument string. If the replacement supplies its own query string, verify whether the old arguments are replaced or retained according to the syntax you chose. Apache’s QSA and QSD make the corresponding choice explicit.

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

Configuration context and rule ordering

Apache processing phases

Apache evaluates rewrite rules in different phases, including URL-to-filename translation and the later fixup phase. A rule in the main server or virtual-host configuration is not processed exactly like the same text in .htaccess. Directory prefixes, internal redirects, and the order of rules can therefore change the result.

  • Put broad rules after specific exceptions so an exception is not swallowed by a catch-all.
  • Use [L] with external redirects so later rules in the current pass do not process the generated URL.
  • Keep an HTTP-to-HTTPS rule separate from application routing when possible; this makes loops easier to identify.
  • After editing a virtual host, validate the active configuration and reload Apache using your operating system’s service procedure.

Nginx location selection and rewrite flow

Nginx first selects a server block by address, port, and host, then chooses a location. Exact, prefix, and regular-expression locations can therefore compete. A rewrite with last starts location selection again; break stops that restart and continues in the current location.

  • Use an exact location for a single legacy URL when a broader prefix also exists.
  • Place host canonicalization in the old host’s server block rather than trying to infer the host inside application logic.
  • Use last only when the resulting URI should be handled by another location.
  • Use break when restarting would send the request back through the same transformation.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Apache and Nginx compared

Decision point Apache Nginx
Fixed redirect Redirect is concise and works in supported server, virtual-host, directory, and .htaccess contexts. return is the simplest directive in a server or location block.
Conditions and regular expressions mod_rewrite provides conditions, captures, and flags such as R, L, QSA, and QSD. rewrite handles regular-expression transformations; location matching supplies much of the routing structure.
Per-directory control .htaccess can be useful when you cannot edit the virtual host, but its pattern context and processing phases differ. Configuration is normally centralized; there is no direct .htaccess equivalent.
Path preservation Capture and reuse path components, and choose query behavior with rewrite flags. Use captured variables or $request_uri; verify how replacement arguments affect the original query string.
Ordering and loops Rule order, internal redirects, and missing [L] can cause repeated processing. Location precedence plus last versus break determines whether matching starts over.
Best default Start with Redirect for a fixed mapping; move to mod_rewrite only for a real condition or transformation. Start with return for a fixed destination; use rewrite for regex-driven changes.

Secure redirect destinations

A redirect should normally point to a fixed, administrator-controlled URL. Building the destination from an unvalidated query parameter, host header, path fragment, or other user input can create an open redirect. Attackers can abuse such a URL in phishing links, obscure the real destination behind a trusted domain, or interfere with authentication flows.

  • Use a fixed canonical scheme and host in rules that perform domain or HTTPS migration.
  • If a destination must be selectable, validate it against an explicit allowlist of schemes, hosts, and permitted paths.
  • Do not concatenate arbitrary user input into an Apache external redirect.
  • Do not pass a user-controlled proxy target to Apache’s [P] flag; Apache identifies that pattern as an SSRF risk.
  • Normalize and validate encoded characters before making security decisions, because alternate spellings can bypass a superficial allowlist.

Do not use a redirect as access control. A client can ignore it, call the destination directly, or submit a different method. Protect the destination itself with authentication and authorization where required.

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

Test a redirect before making it permanent

  1. Check the rule in a staging host or with a narrowly scoped temporary 302.
  2. Request the exact old URL, including a representative query string and any meaningful trailing-slash variant.
  3. Inspect the first response’s status code and Location header rather than looking only at the final browser page.
  4. Confirm that the destination has the intended scheme, host, path, encoding, and query parameters.
  5. Follow the redirect chain and make sure there is no HTTP-to-HTTPS or host-canonicalization loop.
  6. Test an unrelated URL to verify that a broad rule has not captured more traffic than intended.
  7. Test methods your application uses, such as GET, POST, and HEAD, especially when choosing between 302 and 307.
  8. Review server logs for repeated requests, invalid URI warnings, unexpected status codes, and application errors.
  9. Only after the destination is stable, replace the temporary response with a 301 and deploy it during a controlled change.

A command-line check makes the first hop visible. For example, with a client that shows headers:

curl -I https://www.example.com/old-page?source=test

Look for one expected 301 or 302 response and a correctly formed Location header. Add the client option that follows redirects only after inspecting the first hop; otherwise a loop can be hidden behind the final error.

Troubleshoot common failures

The rule never matches

  • In Apache .htaccess, remove the leading slash from a pattern that was written for server context.
  • Confirm that the relevant Apache module is enabled and that the directory permits overrides when using .htaccess.
  • In Nginx, verify that the request reaches the intended server block and that an exact or regular-expression location is not taking precedence.
  • Check spelling, URL encoding, and trailing slashes in the request actually sent by the client.

The browser reports too many redirects

  • Inspect every hop with headers and identify whether the loop alternates between HTTP and HTTPS, old and new hosts, or two path variants.
  • Behind a proxy, replace an origin-side %{HTTPS} check with a check of a trusted, proxy-overwritten protocol header.
  • Make sure the destination no longer satisfies the source rule.
  • In Nginx, avoid last when restarting location selection sends the rewritten URI back into the same rule; use break or a more specific location where appropriate.

The path is right but parameters are wrong

  • In Apache, decide explicitly between retaining, appending, or discarding the original query string with normal rewrite behavior, QSA, or QSD.
  • In Nginx, check whether the replacement introduces a query string and whether the original arguments are consequently retained or replaced.
  • Test duplicate parameter names and encoded ampersands, not just a single simple parameter.

The redirect works in a browser but breaks an API client

  • Confirm the client follows redirects at all; many HTTP libraries require an option to enable that behavior.
  • Check whether the client changes the method or drops a request body after a 301 or 302.
  • Use 307 when preserving the method is required, and test it with the actual client library.

Practical decision guide

  1. Is the move temporary? Start with 302. Use 307 instead when method preservation is a requirement.
  2. Is the destination one fixed URL? In Apache choose Redirect; in Nginx choose return.
  3. Does the rule depend on a condition or captured path? Use Apache mod_rewrite or Nginx rewrite.
  4. Is this a whole-domain or HTTP-to-HTTPS migration? Use a dedicated virtual host or Nginx server block and preserve the request path deliberately.
  5. Should incoming parameters survive? Decide that explicitly, document it in the rule, and test both empty and populated query strings.
  6. Could any destination component come from a request? Replace it with a fixed value or validate it against an allowlist before redirecting.
  7. Have you verified the first response? Inspect status and Location, then check the complete chain and unrelated URLs before switching to 301.

Example rule sets by task

One permanent path move

Apache:
Redirect permanent "/docs/v1" "https://www.example.com/docs/v2"

Nginx:
location = /docs/v1 {
    return 301 https://www.example.com/docs/v2;
}

Temporary campaign preview

Apache:
Redirect temp "/spring" "https://www.example.com/preview"

Nginx:
location = /spring {
    return 302 https://www.example.com/preview;
}

Pattern-based section move

Apache:
RewriteEngine On
RewriteRule "^/manual/(.*)$" "https://www.example.com/guide/$1" [R=301,L]

Nginx:
rewrite ^/manual/(.*)$ https://www.example.com/guide/$1 permanent;

These examples intentionally keep the destination fixed and make the status obvious. Adapt the source pattern, host, and query-string behavior to the URLs you actually own, then test the first response before publishing the rule.

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.

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