October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober 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 Change the Document Root Using an .htaccess File

An .htaccess file cannot change Apache’s server-wide DocumentRoot, but mod_rewrite can route URLs into a subdirectory. Follow the required settings, working patterns, RewriteBase guidance, and troubleshooting steps.
Length9 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You cannot change Apache’s server-wide DocumentRoot directive from an .htaccess file. An .htaccess file works at directory level: with mod_rewrite, it can internally route requests into a subdirectory while leaving the browser’s URL unchanged. If you control the virtual-host or main Apache configuration and the site’s files genuinely belong in a different directory, changing DocumentRoot there is the cleaner solution.

The right approach depends on whether you need a temporary per-directory routing rule, a front-controller application, or a real filesystem-root change. The examples below show where the file goes, which Apache settings are required, how to avoid rewrite loops, and how to diagnose a rule that appears to do nothing.

As an Amazon Associate I earn from qualifying purchases.

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.

What an .htaccess file can and cannot change

DocumentRoot is a server and virtual-host setting. It tells Apache which filesystem directory represents the URL root for a host. Apache reads that directive from the main configuration or a <VirtualHost> block; it is not an .htaccess directive.

An .htaccess file is processed in a directory after Apache has selected the host and its configured document root. Its job is to apply per-directory overrides, including URL rewriting when mod_rewrite is enabled. A rewrite can make a request for / or /play fetch a file from a subdirectory such as /var/www/site/app, but that does not make /var/www/site/app the server’s actual document root.

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

This distinction matters for relative paths, access rules, aliases, logging, and any other virtual host that uses the same root. Apache’s own guidance is that, when all content has really moved into a new directory, changing DocumentRoot or moving the content is preferable to maintaining a rewrite workaround.

Choose the correct method

Method Where it is configured Does the browser URL change? Does the filesystem root change? Best use Main risk
Change DocumentRoot Main Apache configuration or virtual host No Yes You administer the server and the site genuinely lives in the new directory Requires configuration access and an Apache reload or restart
Internal rewrite in .htaccess Per-directory file under the active document root No No Shared hosting or a controlled URL-to-subdirectory mapping Rewrite loops, incorrect relative paths, and rules being ignored by server policy
External redirect .htaccess or virtual-host configuration Yes No The public address should visibly move to another path or host Changes bookmarks and can create redirect chains
Alias mapping Main Apache configuration Usually no No A URL path must map to a directory outside the document root Not normally available when you only have .htaccess access

If you have virtual-host access and every page, asset, and upload now belongs below one directory, use the first option. If you only have shared-hosting access, an internal rewrite is the practical substitute.

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

Prerequisites before editing .htaccess

Put the file in the directory Apache is actually serving

For a site whose configured root is /var/www/htdocs, the relevant file is normally /var/www/htdocs/.htaccess. A file in a parent directory, a sibling directory, or the target subdirectory cannot replace the root-level rules unless Apache is configured to search there. Confirm the active virtual host and its DocumentRoot with the administrator or hosting panel rather than assuming the path from your FTP account is the path Apache uses.

Allow rewrite directives

The virtual host must permit overrides for the directory. Apache documents this minimum setting:

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
<Directory "/var/www/htdocs">
    AllowOverride FileInfo
</Directory>

AllowOverride All also permits the rewrite directives, but it grants substantially more override authority than many sites need. Without at least AllowOverride FileInfo (or AllowOverride All), rewrite directives in .htaccess are silently ignored.

Apache’s core directive documentation places RewriteEngine, RewriteOptions, RewriteBase, RewriteCond, and RewriteRule under the AllowOverride controls. The server must also have mod_rewrite loaded. In per-directory rewriting, Apache requires either Options FollowSymLinks or Options SymLinksIfOwnerMatch; your host may set this globally or restrict whether you can change it in .htaccess.

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

Back up and test one rule at a time

Keep a copy of the current file before adding a rule. Test a normal page, a real static file, a missing path, and the application’s entry URL. A syntax error or redirect loop can make the whole site return a server error, so make changes during a window in which you can restore the previous file or contact the host.

Point a URL path at a subdirectory with an internal rewrite

Suppose the active document root is /var/www/htdocs and an application is physically stored in /var/www/htdocs/app. If visitors should request /app/level-1 while Apache serves app/level-1, the documented per-directory pattern is:

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)
RewriteEngine On
RewriteRule ^app(?:/(.*))?$ app/$1 [L]

In an .htaccess context Apache removes the directory prefix before matching the pattern. That is why the pattern starts with ^app, not ^/app. Apache explicitly notes that a pattern beginning with ^/ will never match in this context. The substitution is also relative: app/$1 means the app directory below the directory containing this file.

This particular rule handles requests that already use the /app URL prefix. If the desired public URL is the domain root—for example, visitors request /level-1 but the files live in the app subdirectory—use a root-level rule that excludes the target prefix on subsequent passes:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/app(?:/|$)
RewriteRule ^(.*)$ app/$1 [L]

Place this version in the current document-root directory. The condition prevents Apache from rewriting an internally generated /app/... request back into app/app/..., which is a common loop or duplicated-path failure. The browser continues to display the original URL because this is an internal rewrite, not a redirect.

How to adapt the root-to-subdirectory rule

  1. Replace app with the directory name relative to the active document root, without a leading filesystem slash.
  2. Keep the RewriteCond exclusion aligned with that same URL prefix, including its trailing-slash alternative.
  3. Leave the RewriteRule pattern without a leading slash. Apache has already stripped the per-directory prefix.
  4. Request the site root and a nested path, then inspect the server log if either request produces a loop, 404, or 403 response.

Do not use this technique to hide a directory that should have its own authentication, uploads policy, or separate virtual host. Those boundaries are clearer and safer when expressed in the main server configuration.

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 a front controller in a subdirectory

Many applications store a single entry script such as index.php in a subdirectory and expect every non-file URL to reach it. For an application at /myapp, a documented .htaccess pattern is:

RewriteEngine On
RewriteBase /myapp/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]

The two conditions preserve existing files and directories. CSS, JavaScript, images, downloads, and real directories can therefore be served normally, while an application route such as /myapp/profile is sent to index.php. The rule is normally placed in the application’s own directory, so its substitution is simply index.php.

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

Apache notes that FallbackResource can be simpler and more efficient for this particular front-controller use case. It is configured by the server administrator, so it may not be available on shared hosting. Use it when you control the virtual-host configuration and do not need the conditional rewrite behavior supplied by RewriteCond.

When RewriteBase matters

RewriteBase supplies the URL prefix Apache uses when it turns a relative substitution back into a URL path. It matters when the URL path and filesystem path do not line up—for example, when the directory is exposed through an Alias, a symlink, or another mapping boundary.

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.

It is not a universal requirement. A relative substitution inside a normally mapped directory often works without it. An absolute URL-path substitution or a full-URI substitution does not use RewriteBase. Add or correct the directive only after confirming that the URL-to-filesystem mapping is the problem; adding it blindly can conceal a misplaced rule.

Situation Typical treatment
Root URL maps directly to the directory containing .htaccess Start with a relative substitution and no RewriteBase.
Application is served below a URL prefix such as /myapp/ RewriteBase /myapp/ may be appropriate for relative substitutions.
URL is provided by an Alias or symlink mapping Check the mapping and use RewriteBase when Apache needs the explicit URL prefix.
Substitution is an absolute URL path or complete URI RewriteBase is not used.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why a RewriteRule appears to do nothing

  1. Verify the file’s location. Make sure the .htaccess file is inside the directory used by the active virtual host, not merely a directory visible in your hosting account.
  2. Check AllowOverride. Ask the administrator to confirm AllowOverride FileInfo or AllowOverride All for that directory. If overrides are disabled, Apache ignores the rewrite directives rather than applying a weaker version of them.
  3. Confirm mod_rewrite. On a server you administer, check the loaded modules and virtual-host configuration. On managed hosting, the provider must enable it.
  4. Remove a leading slash from the pattern. In .htaccess, use ^app or ^(.*)$, never ^/app. Apache strips the directory prefix before matching.
  5. Check the substitution and loop guard. A root-to-subdirectory rule needs a condition that excludes the target prefix on the next internal pass. Otherwise paths can become app/app/... or trigger an internal redirect limit.
  6. Review RewriteBase only for a mapping mismatch. If the filesystem path and URL prefix differ because of an alias or symlink, supply the correct URL base. Do not use it to compensate for a rule placed in the wrong directory.
  7. Read the Apache error log. Messages about too many internal redirects, forbidden rewrite processing, invalid directives, or a missing file identify different faults. Restore the previous file if the site becomes unavailable, then correct one issue at a time.

Common symptoms and likely causes

Symptom Likely cause First check
The original page loads and the rule has no effect Overrides are disabled, mod_rewrite is unavailable, or the rule is in an inactive directory AllowOverride, module status, and active DocumentRoot
Every request becomes a 404 The substitution points to the wrong relative directory or the target file does not exist Resolve the substitution from the directory containing .htaccess
URLs become app/app/... The rule rewrites its own target on a later pass Add or correct the REQUEST_URI exclusion
Apache reports an internal redirect limit A rewrite loop or conflicting rules in parent and child directories Inspect the error log and temporarily disable overlapping rules
Static assets fail while application routes work The front-controller rule is catching real files Use the !-f and !-d conditions
The rule matches nothing The pattern begins with a slash Remove / after the caret

When changing DocumentRoot is the better fix

Use the virtual-host configuration when the directory change is permanent and under your control. A typical configuration is conceptually:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<VirtualHost *:80>
    ServerName example.test
    DocumentRoot /var/www/htdocs/app

    <Directory "/var/www/htdocs/app">
        AllowOverride FileInfo
        Require all granted
    </Directory>
</VirtualHost>

The exact access directives depend on the Apache version and server policy, so do not paste a generic block into production without checking the existing virtual-host configuration. After changing the root, validate the configuration and perform the host’s normal graceful reload. This approach avoids an extra rewrite pass, makes the filesystem and URL roots agree, and removes the need for loop-prevention rules. It also makes the intended root unambiguous to administrators, deployment tools, logs, and security rules.

Decision checklist

  • Need only shared-hosting access? Use an internal rewrite in the active root’s .htaccess.
  • Need the browser to display a different address? Use an explicit redirect instead of an internal rewrite.
  • Have server configuration access and have all content moved permanently? Change DocumentRoot.
  • Serving an application entry script? Preserve existing files and directories with !-f and !-d.
  • Using an alias or symlink? Verify the URL/filesystem mapping and consider RewriteBase.
  • Rule ignored? Check the file location, AllowOverride, and mod_rewrite before changing the pattern.
  • Rule loops? Exclude the target prefix and inspect parent-directory rules and the error log.

Bottom line

An .htaccess file cannot redefine Apache’s DocumentRoot. It can approximate a different root by internally rewriting requests into a subdirectory, provided the active directory allows FileInfo overrides, mod_rewrite is loaded, and the rules use per-directory syntax without a leading slash. For a permanent move when you control Apache, change DocumentRoot directly; reserve .htaccess rewrites for routing that genuinely belongs at the directory level.

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.