Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › 301 redirect

How to Create Temporary and Permanent Redirects in Apache and Nginx

By Freedom251 Team · · 12 min read

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

Use an HTTP 302 when a URL change is temporary and a 301 when the resource has moved permanently. In Apache, Redirect is the shortest option for a fixed mapping, while mod_rewrite handles conditions and regular expressions. In Nginx, use return for a fixed destination and rewrite for pattern-based transformations.

The examples below show where each directive belongs, how to preserve or discard paths and query strings, how to avoid redirect loops, and how to test a rule safely before deploying a permanent redirect.

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.

302 or 301: choose the status before writing the rule

A redirect is an HTTP response containing a status code and usually a Location header. The client then requests the URL in that header.

Use case Status Apache Nginx
Temporary campaign, maintenance page, experiment or short-lived routing change 302 Found Redirect temp, omitted status in Redirect, or [R=302,L] return 302 or rewrite ... redirect
Permanent page, domain or protocol move 301 Moved Permanently Redirect permanent or [R=301,L] return 301 or rewrite ... permanent

Apache’s Redirect directive defaults to a temporary 302 when no status is specified. Apache mod_rewrite also defaults to 302 when the R flag has no number. Nginx’s rewrite directive uses 302 with the redirect flag. A 301 should be used only after the destination, path handling and query-string behavior have been tested, because clients and intermediaries can retain permanent redirect decisions.

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

Do not choose a status merely because the destination is on another host. A host change can be temporary or permanent; classify the business change first. Keep a 302 while a campaign, migration, experiment or maintenance route is still being evaluated, then change the rule to 301 when the old address will no longer be used.

Choose the simplest directive that fits

Server Directive Best for Typical context
Apache Redirect (mod_alias) One-to-one path or host mappings with no conditions Server configuration, virtual host, directory or .htaccess
Apache RewriteRule (mod_rewrite) Regular expressions, conditions, protocol checks and header-based logic Server or virtual-host configuration; also .htaccess when allowed
Nginx return A fixed status and destination server or location block
Nginx rewrite Regular-expression transformations and conditional URI processing server or location block

Prefer the fixed form whenever the destination is fixed. Fewer matching rules mean fewer ordering surprises and less opportunity for a loop. Apache’s Redirect comes from mod_alias, whereas RewriteRule requires the rewrite engine. On Nginx, a return statement is often easier to review than a regular expression when no transformation is needed.

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

Apache redirects

Where Apache evaluates a rule

Place a simple mapping in the virtual host or main server configuration when you control Apache. A hosting account may restrict you to .htaccess; the server must have overrides enabled for redirect directives to work there. Rules in a virtual host and rules in .htaccess do not receive exactly the same URL path, so test the rule in the context where it will run.

Create a permanent path redirect with Redirect

This server- or virtual-host configuration sends a 301 for the old path:

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

permanent means HTTP 301. The path argument identifies the incoming URL path and the final argument is the absolute destination. Apache also supports temp for an explicit 302:

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

Leaving out the status has the same temporary result:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Redirect "/campaign" "https://www.example.com/campaign-preview"

Use this form for a straightforward mapping. It avoids a regular-expression engine and is easier to audit than a rewrite rule.

Map an entire old Apache host

A separate port-80 virtual host is a clear way to move every URL from an old hostname:

<VirtualHost *:80>
    ServerName old.example.com
    Redirect permanent "/" "https://www.example.com/"
</VirtualHost>

The root path makes the rule apply to paths below it as well. Keep the old and new ServerName values distinct; otherwise the destination host can match the same virtual host and redirect repeatedly. Test a nested path and its query string rather than assuming the root example covers every application route.

Use RewriteRule for patterns and conditions

Enable the rewrite engine and capture the changing part of the path:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
RewriteEngine On
RewriteRule "^/old/(.*)$" "https://www.example.com/new/$1" [R=301,L]

The expression captures everything after /old/ and places it after /new/. Change the flag to R=302 for a temporary redirect. Apache recommends using the external-redirect R flag with L: without L, later rules can process the generated redirect again and produce invalid requests or loops.

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.

In a per-directory .htaccess file, Apache removes the directory prefix before matching. For a file at the document root, the equivalent rule is commonly written without the leading slash:

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

Use the form appropriate to the configuration context and verify it with a request to the actual public URL.

Redirect HTTP to HTTPS

When the entire HTTP virtual host should move to HTTPS, Apache’s simple server-configuration pattern is:

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 path slash makes the rule cover every path in that virtual host. Keep the HTTP and HTTPS virtual hosts separate so that the HTTPS host does not redirect back to itself.

If only .htaccess is available, check the connection scheme before redirecting:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule "^(.*)" "https://%{SERVER_NAME}$1" [R=301,L]

Behind a load balancer or reverse proxy, the edge connection to Apache may be HTTP even when the visitor used HTTPS. In that arrangement, test a trusted X-Forwarded-Proto value that the controlled proxy overwrites. Do not accept an arbitrary client-supplied header as proof of HTTPS.

Control Apache query-string behavior

When a rewrite creates a new query string, Apache normally replaces the old one. The QSA flag (query-string append) keeps the original parameters and appends them to the new query string. The QSD flag (query-string discard) explicitly removes the incoming 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]

A request for /search?term=router becomes /results?source=redirect; term=router is discarded because of QSD. If both the new parameter and the old parameters are required, use QSA instead:

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

Decide deliberately whether tracking parameters, filters, authentication tokens or other user data should survive. Do not rely on an accidental default.

Order Apache rules to prevent reprocessing

Apache processes rewrite rules through URL-to-filename and fixup phases. A broad rule placed before a narrow rule can intercept the request first. Put specific exceptions above general redirects, and terminate an external redirect with [L]. If several virtual hosts are configured, confirm that the request reaches the intended ServerName before debugging the rule itself.

Nginx redirects

Put fixed redirects in the matching block

Nginx permits return in a server or location context. For one exact path, an exact-match location and a fixed 301 are clear:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 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
location = /old-page {
    return 301 https://www.example.com/new-page;
}

The temporary equivalent is:

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

Nginx supports redirect response codes including 301, 302, 303 and 307 with return. The first argument is the response code; the optional second argument is the redirect URL (or response text for non-redirect responses).

Transform paths with rewrite

Use a regular expression when several old URLs share a pattern:

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;

Nginx evaluates rewrite directives in a defined sequence. If a rewrite changes the URI and should trigger a fresh location search, add last. If processing should continue in the current location without restarting location selection, use break. Choosing the wrong flag can send a request through the same rule repeatedly or bypass the handler you intended.

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

Canonicalize a host while preserving the path

Use a separate server block for an old hostname 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 query string, so /docs/start?lang=en is sent to the same path and query on the new host. A dedicated server block is preferable to an if-plus-rewrite construction for this task; the latter is unnecessarily cumbersome and can be ineffective.

Preserve or replace Nginx query strings

Nginx carries the original arguments forward when a rewrite replacement does not define a new argument string. If the replacement includes a new query string, it becomes the destination’s argument string. To intentionally remove the old arguments, use the documented empty-argument form (a trailing ? in configurations that use that syntax) and test the resulting Location header. For a fixed destination where query handling must be obvious, a return URL that includes the exact parameters is easier to review.

Apache and Nginx: practical differences

Decision point Apache Nginx
Fixed destination Redirect permanent or Redirect temp return 301 or return 302
Pattern or condition RewriteCond and RewriteRule rewrite with a regular expression; use variables and block selection for conditions
Configuration location Server, virtual host, directory and possibly .htaccess server and location; no per-directory .htaccess equivalent
Temporary default Redirect without a status and R without a number produce 302 rewrite ... redirect produces 302
Rule termination or flow Use [L] with an external R rule Choose last to restart location lookup or break to stay in the current location
Query-string controls QSA appends; QSD discards Original arguments are retained unless replacement syntax supplies or suppresses them

The platforms can produce the same HTTP result, but their processing models differ. Porting a rule line-for-line is less reliable than translating the intent: fixed mapping, pattern transformation, protocol test or host canonicalization.

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.

Security rules for redirects and proxying

Prevent open redirects

Keep redirect destinations in configuration whenever possible. If an application must accept a destination parameter, validate it against an allowlist of schemes, hosts and permitted paths. Never concatenate an unchecked next, url or similar parameter into a Location header. An open redirect can send users to a convincing phishing site and can undermine security checks that trust your domain.

Do not turn user input into an Apache proxy target

Apache’s [P] flag proxies a request rather than merely redirecting it. Passing a user-controlled host or URL to that flag creates a server-side request forgery risk. Restrict proxy destinations to known upstreams and validate both scheme and host before proxying.

Trust forwarded headers only from your proxy

For HTTPS detection behind a load balancer, use a forwarded-protocol header only when the trusted proxy removes and rewrites it. If clients can set the header themselves, they can bypass the condition or create redirect loops.

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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Test a redirect before making it permanent

Test the old URL directly, without following redirects first, so that you can inspect the status and destination:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -I https://www.example.com/old-page

Look for the expected 301 or 302 and a single, correct Location header. To see every hop:

curl -I -L https://www.example.com/old-page

Repeat the test with a representative query string:

curl -I 'https://www.example.com/old-page&page=2'

Before deploying a 301, check all of the following:

  • The old URL returns the intended status code.
  • The Location value has the correct scheme, host, path and encoding.
  • Query parameters are retained, replaced or removed exactly as designed.
  • The destination returns a normal success response and does not redirect back.
  • Both a matching URL and a near miss behave correctly.
  • HTTP-to-HTTPS and old-host-to-new-host rules do not create extra hops or a loop.

After editing Apache configuration, validate the configuration with the server’s configuration-test command before reloading. For Nginx, run the configuration test command supplied by your installation before reload. Keep a temporary 302 while verifying application links, cookies and query handling; change it to 301 only when the mapping is final.

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

Troubleshooting common failures

The rule never matches

Check that the directive is in the active virtual host or server block, that the hostname resolves to that instance, and that the path form matches the context. Apache .htaccess rules commonly omit the leading slash, whereas server-context rules can include it. In Nginx, confirm that a more specific location is not handling the request first.

The browser reports too many redirects

Inspect each hop with curl -I -L. Typical causes are an HTTPS rule that does not recognize the proxy’s forwarded scheme, an old-host rule that also matches the new host, or an Apache rule that continues processing after an external redirect. Correct the scheme test, narrow the host match and add [L] where appropriate.

The path is correct but parameters disappear

Review the query-string decision explicitly. In Apache, add QSA when old arguments must be appended or QSD when they must be discarded. In Nginx, inspect whether the rewrite replacement contains a new argument string or an explicit suppression marker.

A regex redirect rewrites more URLs than intended

Anchor the expression with ^ and $, escape literal dots, and test representative non-matches. Put exceptions above broad rules. A fixed Redirect or return is safer when a regex is not actually needed.

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

The redirect works in one environment but not another

Compare the active configuration context, proxy headers, hostname, URL base path and enabled Apache modules. A rule in .htaccess can behave differently from the same-looking rule in a virtual host, and a load balancer can change the scheme visible to the origin server.

FAQ

How do I create a temporary redirect in Apache?

Use Redirect temp for a fixed mapping, or RewriteRule with [R=302,L] when conditions or a pattern are required. Omitting the status on Redirect also returns 302.

How do I create a permanent 301 redirect in Nginx?

Put return 301 https://www.example.com/new-path; in the matching server or location block. Use rewrite ... permanent only when a regular-expression transformation is needed.

Should I use Apache Redirect or RewriteRule in .htaccess?

Choose Redirect for a direct path or host mapping with no conditions. Choose RewriteRule when you need regular expressions, HTTPS checks, header-based logic or explicit query-string flags. Confirm that overrides allow the selected directive.

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.

How do I preserve the path and query string when changing domains?

In Nginx, a dedicated old-host server block with return 301 https://www.example.com$request_uri; preserves both. In Apache, map the root path in the old virtual host or use a rewrite rule, then test nested paths and representative parameters; use QSA when a new query string must retain the old one.

Why does an HTTPS redirect loop behind a load balancer?

The origin may see HTTP even though the visitor used HTTPS. Check a trusted X-Forwarded-Proto value that the controlled proxy overwrites, and never trust a header clients can set themselves.

How can I intentionally remove query parameters?

Apache’s QSD flag discards the incoming query string. In Nginx, use the documented empty-argument replacement syntax and verify the emitted Location; do not assume parameters disappear by accident.

A concise implementation checklist

  1. Classify the move as temporary (302) or permanent (301).
  2. Choose Redirect or Nginx return for a fixed mapping; choose rewrite rules only when patterns or conditions require them.
  3. Write the rule in the correct Apache context or Nginx server/location block.
  4. Decide whether the original path and query string should be preserved, transformed or discarded.
  5. Terminate Apache external redirects with [L]; select Nginx last or break based on whether a new location lookup is intended.
  6. Keep destinations fixed or validate dynamic destinations against an allowlist.
  7. Test status, Location, query strings and every hop with representative requests.
  8. Deploy a 301 only after the mapping is final and the destination has passed those checks.

Frequently Asked Questions

Can I use a 302 for a domain migration?

Yes, if the move is temporary or still being tested. Use 301 only when the old domain is permanently replaced and its destination has been verified.

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

Does Apache Redirect preserve the unmatched part of a path?

A root or path-prefix mapping can cover subordinate paths, but verify the resulting Location for nested URLs and query strings in the exact virtual-host or .htaccess context you use.

When should Nginx use last instead of break?

Use last when the changed URI should undergo a fresh location lookup. Use break when processing should remain in the current location; restarting a location that contains the same rule can create a loop.

Is a redirect the same as proxying?

No. A redirect sends the client to a new URL. Apache’s [P] flag proxies the request server-side, so an unchecked destination can create an SSRF vulnerability.

The Bottom Line

Use 302 while a route is temporary and 301 only for a tested permanent move. Keep fixed redirects simple, place each rule in the correct Apache or Nginx context, make path and query-string handling explicit, terminate or restart processing deliberately, and validate every destination before production.

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

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.

301 redirect302 redirectApacheHTTP RedirectsNGINXWeb server configuration

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
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.