October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Convert .htaccess Rewrite Rules to Nginx Config

A practical guide to migrating .htaccess rules to Nginx without loops, lost query strings, wrong status codes, or broken front-controller and backend routing.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

There is no line-for-line .htaccess-to-Nginx converter. Apache .htaccess rules run in a per-directory context, while Nginx reads one explicit configuration made of http, server, and location blocks. A reliable migration therefore starts by documenting what each rule does—redirect, internal rewrite, file test, access decision, or backend hand-off—and then expressing that behavior with the Nginx directive that matches the intent.

Use return for unconditional redirects, dedicated server blocks for canonical hosts, try_files for existing-file-or-front-controller routing, rewrite for genuine regular-expression transformations, and a named location or proxy_pass for application backends. Validate with nginx -t, then compare status codes, Location headers, query strings, final URIs, and application logs against the old site.

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.

Why .htaccess rules cannot be copied directly

Apache’s RewriteRule has a pattern, a substitution, and optional flags. RewriteCond lines test expanded values such as the host, port, query string, or filesystem state before the rule runs. The meaning of the pattern also depends on where the rule is defined.

In virtual-host or server context, Apache matches the URL path. In a per-directory .htaccess file, Apache removes the directory prefix before matching. A rule in /blog/.htaccess can therefore see post/, whereas an equivalent Nginx location may see /blog/post/. Relative substitutions, leading slashes, and filesystem paths can all change as a result.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • 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.

Apache also processes per-server rewrites during URL-to-filename translation and per-directory rewrites later, during the fixup phase. Nginx has no per-directory configuration mechanism: every rule must be placed explicitly in an http, server, or location context, with the site’s root, index handling, PHP-FPM settings, and proxy behavior visible in the same configuration.

Think of the migration as a semantic rewrite. Preserve the request outcome, not the original directive spelling.

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

Build an inventory before writing Nginx syntax

Export the complete chain of rules, including inherited files and every condition. For each rule, record the following:

  • Original context: document root, a subdirectory, virtual host, or an included file.
  • Match: the exact path, host, query string, or header tested, including whether Apache had already removed a directory prefix.
  • Action: external redirect, internal URI change, filesystem mapping, access denial, or application hand-off.
  • Conditions: positive and negated tests, their order, and any captures used in the substitution.
  • Status: the intended redirect code, such as 301 or 302, or an internal rewrite with no client-visible redirect.
  • Arguments: whether the original query string is retained, replaced, or discarded.
  • Filesystem assumptions: document root, directory indexes, maintenance files, extension fallbacks, and symbolic links.
  • Terminal behavior: what Apache’s [L], [END], or other flags prevented or allowed in later passes.

Make a test list at the same time. Include canonical and non-canonical hosts, an existing asset, an existing directory, a missing path, a path with encoded characters, a URL with a query string, and at least one route that reaches the application backend.

Map Apache concepts to Nginx contexts

Apache construct Nginx approach Important difference
.htaccess in a directory Explicit server and location configuration Nginx never discovers per-directory files. You must choose the context and add any directory prefix consciously.
RewriteRule used for an unconditional redirect return 301 or return 302 return is clearer and avoids an unnecessary regular-expression pass.
Pattern-based URI transformation rewrite Nginx captures are typically referenced as $1, $2, and so on; choose the processing flag deliberately.
-f and -d file or directory tests try_files Nginx tests paths against the configured root and can fall through to a URI or named location.
Front-controller fallback try_files $uri $uri/ /index.php?$args; The explicit $args preserves the incoming query string.
Application hand-off Named location with proxy_pass, or a PHP-FPM location Keeping filesystem tests separate from proxy settings makes the flow easier to audit.
HTTP_HOST conditions server_name selection or a narrowly scoped condition Positive host definitions and a catch-all default server are usually safer than a complex negated condition.
Apache [L] last, break, a named location, or no rewrite flag last starts a new location search; break stays in the current location. Neither is a mechanical replacement for [L].

Convert canonical-host redirects first

Host canonicalization is best expressed by server selection, not by combining an if statement with a rewrite. Suppose requests for example.org must move to www.example.org while retaining the original path and query string:

server {
    listen 80;
    server_name example.org;
    return 301 http://www.example.org$request_uri;
}

server {
    listen 80;
    server_name www.example.org;
    # normal site configuration
}

$request_uri contains the original path and arguments, so the redirect does not silently lose a query string. Use HTTPS in both the listener and destination when that is the site’s canonical scheme. Use 302 instead of 301 only when the redirect is intentionally temporary; browsers and intermediaries cache 301 responses aggressively.

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.

For requests arriving on unexpected host names, define a default_server catch-all that returns the chosen canonical host. This turns Apache logic such as “every host except these approved names” into explicit server selection and avoids relying on a fragile negative condition. Validate that the redirect cannot point back to the same host, which is a common source of loops.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • 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

Translate WordPress and other front controllers with try_files

The common Apache pattern is: if the request maps to a real file or directory, serve it; otherwise send it to index.php. In Nginx, the direct form is:

server {
    listen 80;
    server_name www.example.org;
    root /var/www/example.org/current/public;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }
}

$uri checks the requested file, $uri/ checks a directory, and the final URI is used only when neither exists. The ?$args suffix carries the incoming query string to the front controller. Omitting it can break searches, filters, pagination, and tracking parameters that the application expects.

The PHP execution block is separate from the routing rule. A typical installation passes index.php to PHP-FPM and rejects or handles other scripts according to the application’s security policy. Do not send every arbitrary path to a script handler simply because the front controller exists; keep the script location narrow and test direct requests to unintended PHP files.

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

Replace multi-stage file checks with a named backend location

Some Apache configurations test a maintenance page, the requested file, an index file, and an extension variant before forwarding anything else to an application cluster. Nginx can express that sequence without a chain of regular expressions:

server {
    listen 80;
    server_name app.example.org;
    root /var/www/myapp.com/current/public;

    location / {
        try_files /system/maintenance.html
                  $uri
                  $uri/index.html
                  $uri.html
                  @app-server_cluster;
    }

    location @app-server_cluster {
        proxy_pass http://app-server;
    }
}

The first existing candidate wins. If the maintenance file exists, every request is served from it; otherwise Nginx checks the requested path and the two fallback forms before entering the named location. A named location is an internal hand-off, not a client redirect, so the browser keeps the original URL. Configure proxy headers, timeouts, buffering, and TLS settings for the upstream separately, and confirm that the upstream name resolves in the Nginx runtime environment.

Use rewrite for real regular-expression transformations

Nginx’s rewrite directive accepts a regular-expression pattern and replacement. Captures from the pattern are available as $1, $2, and later numbers. Rewrite directives execute in order, so put specific transformations before broad ones.

location /legacy/ {
    rewrite ^/legacy/(.*)$ /archive/$1 permanent;
}

This sends a permanent redirect because permanent produces a 301 response. If the client should not see a redirect and the request should be handled internally, use an internal replacement and choose processing behavior based on the desired location search. Use return when no pattern match is needed:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • 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)
location = /old-home {
    return 301 /;
}

Be precise about the context in which the pattern runs. A regular-expression location and a rewrite inside that location do not necessarily see the same path representation as an Apache rule copied from a subdirectory file. Test with and without a leading slash rather than assuming the original pattern can be pasted unchanged.

Choose last and break intentionally

Nginx’s processing flags have different control flow:

  • last stops the current rewrite set and starts a new location search using the changed URI.
  • break stops rewrite processing in the current context and continues there with the changed URI.
  • redirect creates a temporary external redirect.
  • permanent creates a permanent external redirect.

Using last inside a location that also matches the rewritten URI can repeatedly re-enter the same logic. That produces a rewrite loop or a “too many internal redirects” error. Use break when the URI should remain in the current location, or route directly to a named location when the next step is an application hand-off. A rule that was marked Apache [L] may require any of these choices—or no Nginx rewrite flag—depending on whether Apache’s original result was a redirect, a new internal URI, or a filename mapping.

Keep exact-match and narrow prefix locations ahead of broad fallbacks. A catch-all location / should not intercept a path that needs a dedicated static, API, or script policy.

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

Preserve or replace query strings deliberately

Query-string behavior is one of the easiest migration details to lose. For an external redirect, return 301 https://www.example.org$request_uri; preserves the original path and arguments. For a front-controller fallback, /index.php?$args appends the existing arguments to the internal URI.

A rewrite replacement that contains a new question mark defines a new argument string. If the replacement has no question mark, Nginx generally carries the original arguments for an internal rewrite; verify this behavior for each rule rather than relying on memory, especially when the Apache substitution explicitly used a trailing ? to discard arguments. Test an input such as /search?q=arcade&page=2 and inspect both the application’s received parameters and the browser’s visible URL.

Map conditions without recreating Apache’s syntax

Apache conditions can inspect the host, port, query string, request headers, and filesystem. In Nginx:

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • 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
  • Use server_name and separate server blocks for host decisions.
  • Use $request_uri, $uri, and $args for URI and query-string tests.
  • Use try_files instead of repeated filesystem if checks.
  • Use a narrowly scoped if only when a condition cannot be represented by server or location selection; avoid using it as a general programming language.
  • Use maps or named locations when several conditions must feed one stable outcome.

Apache condition captures and rule captures are separate concepts. Recreate each capture deliberately and check which value a replacement references. A host capture should not accidentally be reused as a path capture simply because both were numbered in the original file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common migration failures and their fixes

The rule never matches

Check the context first. A pattern copied from /shop/.htaccess may need the /shop/ prefix in Nginx. Also check whether the Nginx directive sees a leading slash, whether a more specific location won selection, and whether URL decoding changed the characters you are testing.

A redirect loops

Inspect the response’s Location header with a command such as curl -I. Confirm that the destination host differs from the source when canonicalizing hosts, that HTTP and HTTPS blocks do not redirect to each other, and that a rewritten URI does not re-enter the same last rule. A default server should not redirect a request to a name that resolves back to the default server with the same rule.

The browser receives a 200 instead of a 301

The configuration probably performed an internal rewrite or reached a backend that returned 200. Use return 301 or a rewrite with permanent when the client must update its URL. Then test the status code and Location header, not only the final page content.

Arguments disappear

Check every substitution containing ?. Add $args where the application needs the original query string, and verify that a redirect uses $request_uri or an equivalent explicit argument policy.

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

Static files fall through to the application

Confirm the effective root, file permissions, and the exact path tested by try_files. A wrong root makes every file appear missing. Check both an existing file and an existing directory before changing the fallback rule.

Nginx reports too many internal redirects

Look for a last rewrite that targets a URI matched by the same location, a front-controller URI that is routed back through itself, or overlapping regex locations. Replace the loop with break, an exact location, or a named backend location as appropriate.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • 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.

The backend receives an unexpected URI

Compare proxy_pass placement with the selected location and inspect upstream access logs. A proxy hand-off is not the same as an external redirect, and a named location may preserve a different internal URI than a new location search would.

Validate the converted configuration safely

  1. Run nginx -t. Do not reload a configuration that fails syntax or dependency checks.
  2. Reload Nginx using the service method appropriate to the operating system, then confirm the worker processes accepted the new configuration.
  3. Test each canonical host over every configured scheme and port. Record the status code, redirect chain, and exact Location value.
  4. Request a known static file, a known directory, a missing path, and a path that should reach the front controller.
  5. Repeat those requests with query strings, percent-encoded characters, trailing slashes, and unusual but valid path segments.
  6. Exercise at least one PHP-FPM route and one proxied application route. Compare the URI, arguments, host header, and scheme seen by the application.
  7. Inspect Nginx error and access logs alongside application logs. A successful browser render can hide a wrong status code, an extra internal redirect, or a backend retry.
  8. Compare cache behavior and canonical URLs before removing the Apache configuration. Keep a rollback copy until representative traffic behaves identically.

A practical conversion worksheet

For a large site, maintain one row per original rule with these columns:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Column What to write
Source file and directory Every inherited .htaccess path and its effective directory.
Input examples At least one URL that should match and one that should not.
Conditions Host, query, header, and file tests in evaluation order.
Desired result External redirect, internal URI, static file, PHP-FPM, proxy, or denial.
Status and headers Expected status, Location header, and cache implications.
Arguments Preserved, replaced, or intentionally removed.
Nginx context Specific server, exact location, prefix location, regex location, or named location.
Verification The command or request used to prove the result and the observed logs.

This worksheet prevents two frequent mistakes: losing a rule that lived in an inherited directory, and translating a control-flow flag before deciding what the request is supposed to do.

When to simplify instead of reproducing every rule

Apache configurations often accumulated compatibility rules for old URLs, multiple applications, and historical hosting layouts. Nginx does not need a one-for-one copy when several rules have the same outcome. Consolidate canonical-host handling into server blocks, replace repeated file tests with one try_files sequence, and send all application misses to one named backend location when that is the actual contract.

Do not simplify away observable behavior. Keep separate rules when status codes differ, when one path must retain arguments and another must discard them, when a redirect is external but another transformation is internal, or when security and caching policies differ. The goal is fewer moving parts with the same tested outcomes—not fewer lines at any cost.

Final decision guide

  • Choose server selection plus return for canonical host or scheme redirects.
  • Choose try_files for “serve a real file or directory, otherwise use the application” behavior.
  • Choose rewrite only when a regular-expression transformation is genuinely required.
  • Choose break when an internal URI change must remain in the current location.
  • Choose last only when a new location search is intentional and cannot loop.
  • Choose a named location to separate filesystem checks from proxying or another backend hand-off.
  • Choose explicit query-string handling whenever the old rule changed or depended on request arguments.

A successful conversion is demonstrated by equivalent requests and responses, not by similar-looking configuration text. Once every rule has an explicit Nginx context, an intentional status and URI outcome, tested argument behavior, and a verified terminal path, the migration is maintainable instead of merely syntactically plausible.

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.

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.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
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.