DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon 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 Now×
Skip to content
VGSources
Blog

How to Write an .htaccess Rewrite Rule for a Subdomain

A practical Apache guide to subdomain rewrites: test the host with RewriteCond, match paths correctly in .htaccess, choose internal routing or redirects, and fix common loops and 500 errors.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put the subdomain test in RewriteCond %{HTTP_HOST}, then let RewriteRule match the URL path. In an .htaccess file, write the path pattern without a leading slash. Use a relative substitution to route a subdomain into a directory while keeping the same address in the browser, or an absolute URL with a redirect flag when the browser must move to another host.

The rule has two separate jobs

Apache evaluates a subdomain rule in two stages. A RewriteCond checks request metadata such as the host name. The following RewriteRule then checks the URL path. The rule itself cannot test the host: Apache’s documentation states, “The Pattern is matched only against the URL-path — not the hostname, port, or query string.”

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.

That distinction explains most failed subdomain rules. A pattern such as ^app.example.com in RewriteRule is looking for that text in a path, not in the host header, so it will never perform a hostname match. Put the hostname expression in a condition and keep the rule pattern focused on paths such as docs/page.html.

Conditions apply to the next rule. If several RewriteCond directives appear together, every condition must match before Apache applies that rule. Captures made by a condition are referenced as %1, %2, and so on; captures made by the rule pattern are referenced as $1, $2, and so on.

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

Check the server before changing syntax

A perfectly written expression cannot work if the request never reaches the Apache instance or if that directory does not permit overrides. Confirm these prerequisites first:

  • The subdomain has a DNS record resolving to the server that handles the request.
  • The request is accepted by the intended virtual host and uses the document root you expect.
  • mod_rewrite is loaded, and the file contains RewriteEngine On.
  • The directory’s override policy permits rewrite directives in .htaccess files.
  • You know whether the file is in the document root or in a subdirectory; that location changes the path Apache presents to RewriteRule.

If DNS or virtual-host routing is wrong, you may be editing the correct-looking file for a request that is actually being served elsewhere. A 500 response usually points to a configuration or directive problem rather than a mismatch in the regular expression. Check the Apache error log after each change.

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

Internal rewrite: keep the subdomain in the address bar

An internal rewrite changes the file Apache serves without sending a redirect response. The browser continues to display the subdomain. In the document-root .htaccess, this is the basic pattern:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^app.example.com$ [NC]
RewriteRule ^(.*)$ app/$1 [L]

A request for https://app.example.com/docs/page.html is mapped internally to app/docs/page.html beneath the document root. The client does not receive a new URL, and no 3xx status is generated.

Build it safely

  1. Back up the current file. Keep a copy of the working .htaccess before adding a catch-all rule.
  2. Enable rewriting once. Put RewriteEngine On near the start of the relevant rule set. Repeating it is unnecessary.
  3. Anchor the host. The ^ and $ require the complete host to be app.example.com, instead of matching a name that merely contains that text.
  4. Use [NC] when case should not matter. Host names are case-insensitive, so this flag is generally appropriate for a canonical host test.
  5. Use a relative substitution for an internal directory mapping. app/$1 is relative to the current per-directory context.
  6. Stop processing after the mapping. [L] stops the current rewrite set once this rule has matched.

Local testing on a non-default port

During local development, the host header may include a port. The exact-host condition above would not match app.example.com:8080. If that is intentional, make the port optional:

RewriteCond %{HTTP_HOST} ^app.example.com(?::[0-9]+)?$ [NC]

Use the port-aware expression only where you need it. On a normal public request, the host condition usually contains no port, even when HTTPS is in use.

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

Map only a portion of the path

A catch-all rule sends every path on the subdomain into the directory. If only a section should move, narrow the pattern:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^app.example.com$ [NC]
RewriteRule ^docs(?:/(.*))?$ app/docs/$1 [L]

Here, /docs and paths below it are mapped to app/docs. Other paths remain subject to later rules or normal document-root handling. Test the empty and non-empty capture cases so that a request for exactly /docs resolves to the directory you intend.

External redirect: send the browser to another host

Use an absolute URL and a redirect flag when the destination must be visible to the client. For a permanent move from one subdomain to another host:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^old.example.com$ [NC]
RewriteRule ^/?(.*)$ https://www.example.com/$1 [R=301,END,NE]

The response tells the browser to request the new URL. The 301 status communicates that the move is permanent; do not use it for a temporary experiment because browsers and intermediaries can cache permanent redirects. Use a temporary redirect status while testing or while the destination may change.

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

The optional slash in ^/?(.*)$ makes the pattern tolerant of contexts that do or do not present a leading slash. In a normal .htaccess rule, Apache has already removed the directory prefix, so a pattern without a slash is usually clearer.

[END] stops per-directory rewrite processing completely for the request. That is useful when another pass through nested .htaccess files could redirect the request again. The [NE] flag prevents Apache from escaping special characters in the redirected URL. Keep it only when you understand the encoding of the captured path; ordinary redirects are safer without it if you do not need that behavior.

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)

Redirect versus internal rewrite

Question Internal rewrite External redirect
What does the browser display? The original subdomain and path remain visible. The browser changes to the absolute destination URL.
What response does the client receive? Normally the final resource response, such as 200. A 3xx response, such as 301, followed by a new request.
Does the host change? No; Apache serves a different internal path. Yes, when the substitution contains another host.
Where can the destination live? Typically inside the same document root and server context. Any reachable URL, including another server.
What are the operational consequences? No extra client round trip and no visible URL change. The redirect can be cached and carries permanent or temporary move semantics according to its status.

Choose the internal form for host-based routing where the subdomain is an alternate entry point to content on the same site. Choose a redirect when the old host should no longer be used, when canonical URLs must be exposed, or when the content has moved to another service.

Why a leading slash usually fails in .htaccess

In server or virtual-host configuration, examples often show a path beginning with /. Per-directory rewriting is different: Apache removes the matched directory prefix before it evaluates the RewriteRule pattern. In a document-root .htaccess, a request for /docs/page.html is therefore matched as docs/page.html, not /docs/page.html.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
File location Request Typical path seen by the rule
Document root .htaccess /docs/page.html docs/page.html
/app/.htaccess /app/docs/page.html docs/page.html
Virtual-host/server context /docs/page.html Context-dependent server path, commonly including the leading slash

That is why RewriteRule ^(.*)$ app/$1 [L] is the normal document-root form. If you copy a server-context pattern beginning with / into a per-directory file, it may never match.

The query string is not part of the rule pattern either. A request such as /docs/page.html?mode=print still matches the path docs/page.html. When a substitution does not add a new query string, Apache normally carries the existing query string forward.

Prevent loops and repeated directory prefixes

A broad rule can process its own destination on a later rewrite pass. For example, the internal rule that maps everything to app/ could see the resulting app/docs/page.html and prepend app/ again. Exclude the destination before the catch-all:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^app.example.com$ [NC]
RewriteRule ^app(?:/|$) - [END]
RewriteRule ^(.*)$ app/$1 [L]

The first rule leaves paths already beginning with app alone. The dash substitution means “do not change the path.” Use [END] when you need to prevent additional per-directory passes; use [L] when stopping only the current rule set is sufficient.

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

Static files and directories may also need to bypass a catch-all routing rule. Add exclusions before it when the subdomain must serve existing assets directly:

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [END]

The two conditions together match an existing file or directory. Place this block only if that behavior fits your layout; otherwise, it can prevent the application directory from receiving paths that it is supposed to handle.

Make host matching precise

Anchor the expression

Use ^old.example.com$, not an unanchored fragment such as old.example.com. Anchoring prevents a related but unintended host from entering the same rule. If several aliases are deliberately equivalent, express those aliases explicitly and document why they share a destination.

Account for ports deliberately

The host value can include a port during local testing. Either test with a host expression that permits an optional numeric port or send the request through the normal public port before evaluating the rule. Do not remove the end anchor simply to make a development request match; that can accept unrelated host names.

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

Order HTTPS and host canonicalization

Many sites have separate rules for HTTP-to-HTTPS and host canonicalization. Decide which URL is canonical, then order the conditions so one request does not satisfy a rule that sends it back to a host still covered by the same condition. A redirect loop commonly occurs when the destination host continues to match the source condition or when two independent redirects alternately rewrite the request.

Document-root and subdirectory placement

An .htaccess file applies to its directory and descendants. A file in the document root can see all paths below that root, while a file in /app sees paths relative to /app. Relative substitutions are interpreted in that per-directory context, so moving the file can change the meaning of a rule even when the text is unchanged.

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.

For a subdomain-to-directory mapping, place the rule in the document root when the target directory is a sibling such as /app. If the rule is placed inside /app, it cannot serve as the same top-level entry-point rule because requests have already been narrowed to that directory’s scope.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

.htaccess compared with virtual-host configuration

Factor .htaccess Virtual-host/server configuration
Administrative access Useful when you can edit a site directory but not the main Apache configuration. Requires server administration access.
Scope Limited to one directory and its descendants. Can be defined for an entire virtual host and ordered with other server rules.
Maintenance Convenient for site-level deployments, but rules can be scattered across directories. Centralized and easier to audit when several hosts share canonicalization policies.
Performance and control Apache checks per-directory configuration during request processing. Rules are loaded with the server configuration and avoid per-directory discovery.
Alternative redirect directive Use mod_rewrite directives permitted by the directory override policy. Apache’s remapping guidance identifies a dedicated Redirect in a <VirtualHost> as the cleanest choice when server configuration access exists.

If you control the virtual-host configuration, a host-level redirect or dedicated virtual host is usually easier to reason about than a distributed set of .htaccess files. Use .htaccess when deployment constraints make it the appropriate control point.

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

A cautious testing procedure

  1. Test a harmless path first. Use a temporary redirect status or a narrow internal rule while confirming the host and path behavior. Avoid publishing a 301 until the destination is final.
  2. Verify DNS and virtual-host selection. Confirm that the subdomain resolves to the intended server and that the request lands in the expected document root.
  3. Check an unmistakable file. For an internal mapping, request a file that exists only under the destination directory so a successful response proves the mapping occurred.
  4. Inspect redirect headers. Run a header request such as curl -I https://old.example.com/test and check the status and Location value. A redirect should point to the intended host exactly once.
  5. Test both host cases and paths. Check the root path, a nested path, a path that should be excluded, and a request with a query string.
  6. Read the error log after failures. A syntax error, forbidden directive, or rewrite loop is usually identified there more clearly than in the browser’s generic 500 page.
  7. Clear cached redirects when changing tests. Browsers may remember a 301, so use a fresh profile or a command-line client when validating a changed destination.

Troubleshooting by symptom

The rule never matches

  • Confirm that RewriteEngine On appears in the active file.
  • Check that mod_rewrite is loaded and that the directory override policy allows rewrite directives.
  • Remove the leading slash from a pattern copied into .htaccess.
  • Check the actual host, including an optional development port, against the anchored condition.
  • Verify that DNS and the virtual host point to the server containing this file.

Apache returns 500

Inspect the error log first. Common causes include a misspelled directive, an unsupported flag, a malformed regular expression, or a directory policy that disallows the directive. Fix the first configuration error reported, reload or retest, and then evaluate the rule’s logic.

The browser keeps redirecting

Compare the source condition with the destination host. If the destination still satisfies the source condition, the rule can redirect repeatedly. Also inspect separate HTTP-to-HTTPS and canonical-host rules for conflicting order. Test with a command-line client so cached 301 responses do not hide the current behavior.

The destination path gains repeated prefixes

Add an exclusion for the destination directory before the catch-all rule. Then choose [L] or [END] according to whether later per-directory passes must be prevented.

The wrong file is served

Check the location of the .htaccess file and the document root selected by the virtual host. A relative substitution is resolved in the current directory context, so a rule copied from the document root may point somewhere else when placed in a child directory.

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

Reusable rule patterns

Route an entire application subdomain internally

RewriteEngine On
RewriteCond %{HTTP_HOST} ^app.example.com$ [NC]
RewriteRule ^app(?:/|$) - [END]
RewriteRule ^(.*)$ app/$1 [L]

The exclusion protects the destination directory, while the final rule maps every other path on the application subdomain into it.

Redirect an old subdomain permanently

RewriteEngine On
RewriteCond %{HTTP_HOST} ^old.example.com$ [NC]
RewriteRule ^/?(.*)$ https://www.example.com/$1 [R=301,END]

Leave out [NE] unless you have a specific reason to control escaping. The captured path is appended after the destination host, and an existing query string is normally retained because the substitution does not define a new one.

Support a local port without weakening the host test

RewriteEngine On
RewriteCond %{HTTP_HOST} ^app.example.com(?::[0-9]+)?$ [NC]
RewriteRule ^(.*)$ app/$1 [L]

This accepts the normal host and a numeric development port while still rejecting unrelated host names.

Deployment checklist

  • DNS resolves the subdomain to the Apache server.
  • The intended virtual host and document root receive the request.
  • mod_rewrite is enabled and RewriteEngine On is present.
  • The directory policy permits the rewrite directives used.
  • The host condition is anchored and includes a port only when required.
  • The RewriteRule pattern reflects the path form used by .htaccess, normally without a leading slash.
  • An internal route uses a relative destination; a visible move uses an absolute URL and an intentional redirect status.
  • Destination paths and existing files or directories are excluded before a broad catch-all where necessary.
  • Temporary tests are complete before enabling a permanent 301.
  • The error log and response headers have been checked for every failure or loop.

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.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver 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.