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 Redirect a Domain to a Subfolder With .htaccess (Internal Rewrite or Visible Redirect)

Use Apache .htaccess to serve a domain from /public without exposing the folder, or redirect visitors to a visible /public URL. This guide explains per-directory matching, loop prevention, host and HTTPS checks, troubleshooting and curl verification.
Length10 min Posted Quest giverVGSources Team

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.

To serve your domain from a physical /public folder without showing that folder in the address bar, use an internal Apache rewrite in the document-root .htaccess file. To make visitors see /public, use an external 3xx redirect instead. The two outcomes use similar rules but have different browser, caching, SEO and security consequences.

The examples below assume DNS already points example.com to this Apache site, the file is in the document root, the content is in a real public directory, and mod_rewrite is enabled.

As an Amazon Associate I earn from qualifying purchases.

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

Choose whether the folder should be hidden

First decide what the public URL should be. An internal rewrite changes where Apache looks for a file while leaving the requested URL unchanged. An external redirect sends a response back to the browser, which then requests a new URL and displays it.

Goal What the browser sees Apache action Typical use
Hide the folder https://example.com/game Internal rewrite to public/game; no 3xx response A document root whose application files live below public
Show the folder https://example.com/public/game External redirect with a 3xx status and Location header Making an existing subfolder URL canonical or moving visitors to a new public path

A path substitution without the R flag is internal. A fully qualified substitution such as https://example.com/..., or a rule carrying R=302 or R=301, is external. Do not use a visible redirect when the requirement is specifically to conceal the folder: it will necessarily expose /public in the address bar.

How Apache evaluates a .htaccess rule

RewriteRule matches a path, not a hostname

RewriteRule receives the URL path. It does not test whether the request was for example.com, www.example.com or another virtual host. Hostname checks belong in RewriteCond, normally against %{HTTP_HOST}.

Per-directory rules have a relative pattern

In a document-root .htaccess file, Apache removes that directory prefix before matching the rule. Consequently, a root rule starts with ^, not ^/. A rule copied from a virtual-host configuration can fail if its leading slash is left in place. A .htaccess file placed inside /public has a different relative context and should not be treated as interchangeable with the root file.

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

Processing stops differently with END and L

[END] stops all per-directory rewrite processing for the current request and is documented for Apache 2.4. On a server where [END] is unavailable, use [L] and keep the destination-prefix exclusion; without that exclusion, another per-directory pass can prepend public repeatedly.

Internal rewrite: keep /public out of the browser URL

Use this document-root rule

Put the following in the .htaccess file at the site’s document root:

RewriteEngine On

# Apply only to the intended host.
RewriteCond %{HTTP_HOST} ^(?:www.)?example.com$ [NC]

# Do not prepend /public a second time.
RewriteCond %{REQUEST_URI} !^/public(?:/|$) [NC]

# In document-root .htaccess, the RewriteRule pattern is relative.
RewriteRule ^ public%{REQUEST_URI} [END]

The first directive enables the rewrite engine for this directory. The host condition limits the rule to the intended bare domain and its www variant, case-insensitively because of [NC]. Replace the example domain with your actual, allowlisted hostname.

The second condition is the loop guard. If the incoming path is already /public or begins /public/, the rule does not add another prefix. The non-capturing group (?:/|$) prevents a path such as /publicity from being mistaken for the destination directory.

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.

The rule’s pattern ^ matches every relative path in this root context. The substitution joins public to the original request path. A request for / is therefore served from the public directory, while /assets/app.css is read from public/assets/app.css. Because there is no R flag and no absolute URL, Apache serves the rewritten file internally and the address bar remains unchanged.

What happens to query strings

The substitution does not add a question mark or a new query string. Apache therefore carries the original query string through the rewrite under its normal mod_rewrite rules. A request such as /search?q=arcade is looked up below public/search with q=arcade still available to the application. If you later add a substitution containing a new query string, specify deliberately whether the original should be replaced, appended or discarded; do not assume every custom rule preserves it.

Ensure the destination contains the complete site

The physical public directory must contain the entry point, static assets, uploads or application routes that the site needs. The rewrite changes the filesystem lookup; it does not copy files, change Unix permissions, create an index file or configure a framework’s front controller. If public/index.php is the entry point, normal DirectoryIndex behavior still has to be available. If the application expects all unknown paths to reach a front controller, its own rules must run after this mapping and must be compatible with the new directory location.

Do not create a second competing root rule

Use one clear root mapping. A second rule that also prepends /public, an application-generated canonical redirect, or an HTTP-to-HTTPS rule can interact with the mapping and produce multiple hops. Keep the folder mapping, host canonicalization and scheme canonicalization logically separate, then test their combined behavior.

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

Visible redirect: make the browser show /public

Start with a temporary redirect

If the public URL should include the folder, use this in the document-root .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www.)?example.com$ [NC]
RewriteCond %{REQUEST_URI} !^/public(?:/|$) [NC]
RewriteRule ^ https://example.com/public%{REQUEST_URI} [R=302,END,NE]

The fully qualified substitution and R=302 make the response external. The client receives a temporary redirect and then requests, for example, https://example.com/public/game. The same destination-prefix condition prevents a request already under /public from redirecting to /public/public/game.

NE means Apache should not unnecessarily escape special characters in the redirect target. Test paths containing encoded characters before relying on it; URL construction still needs to be correct for your application. The fixed destination host is intentional: it avoids copying an untrusted value from the request into a redirect URL.

Change to 301 only after testing

After confirming HTTP and HTTPS behavior, both host variants, existing and missing paths, query strings and already-prefixed URLs, change R=302 to R=301 only if the move is genuinely permanent. Browsers and intermediary caches can retain a 301, so a mistake can persist after the rule is corrected. During development, clear cached redirects or use a fresh profile and inspect the response with a command-line client.

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

Do not redirect to the same visible URL

A redirect is useful only when the target differs from the request. Keep the exclusion for /public; otherwise the rule redirects its own destination and can create an endless sequence of identical or increasingly prefixed URLs.

When server configuration is available

If you administer the main Apache configuration, a dedicated virtual host with a simple Redirect directive is Apache’s preferred approach for straightforward host moves. It is handled outside per-directory rewriting and avoids many context and pass-through surprises. That option is appropriate when the operation is a simple URL move and you can edit the virtual-host configuration.

Shared hosting and managed platforms often expose only .htaccess. In that case, mod_rewrite is the appropriate mechanism, but the server must permit overrides for the directory (for example, an AllowOverride setting that permits the required directives). If the file is ignored, no rewrite pattern can compensate for a host that disallows overrides.

Host, HTTPS and proxy details

Allow only the hosts you intend

The sample condition accepts the bare and www names. Decide whether one should be canonical. If you want only one, use a separate, explicit canonical-host rule and test it before combining it with the folder mapping. Some requests include a port in HTTP_HOST; if your deployment exposes non-standard ports, make the condition match the exact host format your server receives rather than weakening it to an arbitrary substring.

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

Do not infer the original scheme blindly

When TLS terminates at a reverse proxy or load balancer, Apache may receive an internal HTTP connection even though the visitor used HTTPS. An HTTP-to-HTTPS condition based on the wrong variable can create a loop or redirect every request unnecessarily. Confirm which trusted proxy signal represents the original scheme, configure that signal securely, and then test direct and proxied traffic separately. Avoid stacking an independent HTTPS redirect on top of the folder rule until each response is understood.

Keep the destination host fixed

Apache warns that building redirect URLs from unvalidated request input can create an open redirect. Do not concatenate an arbitrary Host header into the destination. Use an allowlisted RewriteCond and a literal destination such as https://example.com. Host validation also prevents an unexpected virtual host from receiving a redirect intended for your site.

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

Common failures and their fixes

The rule never matches

  • Check that the rule is in the document-root .htaccess, not in a parent directory or an unrelated application directory.
  • Remove a leading slash from the RewriteRule pattern in per-directory context. Use ^, not ^/.
  • Confirm that mod_rewrite is loaded and that the virtual host permits the directives used in .htaccess.
  • Verify that DNS and the request’s Host header reach the virtual host containing this file. A different virtual host can serve the request without reading your rule.

Apache reports a syntax or unknown-flag error

Check the installed Apache version and the hosting provider’s supported flags. If [END] is not available, replace it with [L] and retain the destination-prefix exclusion. Do not remove the loop guard merely to make a rule parse.

The URL becomes /public/public/…

The destination exclusion is missing, misspelled or testing a different path than the one Apache sees. Ensure it is evaluated before the rule that prepends public, and that both /public and /public/... are excluded. Also inspect other .htaccess files: a nested file may be applying a second prefix.

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

Everything returns 404

Confirm the physical path and capitalization of the public directory, then test a known file such as public/robots.txt. A successful rewrite cannot serve a file that does not exist or that the process cannot read. If static files work but application routes fail, inspect the application’s own front-controller rules and its base-URL setting.

The browser keeps redirecting

Use a client that does not automatically follow redirects and inspect each response. Determine whether the loop is between HTTP and HTTPS, between two hostnames, or caused by the folder rule seeing its own destination. Proxy scheme headers, a second canonicalization rule and an incorrect host condition are common causes.

Query parameters disappear

Compare the original request and the final request with a client that prints headers. The supplied mapping does not introduce a new query string, so investigate later rules, application redirects and any substitution containing ?. A framework can also issue its own redirect that omits parameters even when Apache preserved them initially.

The rule works on one hostname but not the other

Inspect the exact value received in HTTP_HOST, including case and any port. Update the allowlist deliberately rather than replacing it with a broad wildcard. If one hostname is supposed to redirect to the other, make that policy a separate rule so the folder mapping remains easy to reason about.

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

Verification procedure before going live

Run checks against a staging hostname or use a temporary redirect first. The following matrix catches the mistakes that are otherwise hardest to see:

  1. Request the root over HTTP and HTTPS. For an internal rewrite, confirm the response serves the home page without changing the URL. For an external redirect, confirm the intended 3xx status and a single Location header.
  2. Request a nested route such as /games/zelda. Confirm it maps to the corresponding path below public and does not gain a second prefix.
  3. Request a known static file, for example /assets/site.css, and verify a successful content response rather than an HTML fallback or a redirect loop.
  4. Request a missing path and confirm the application’s intended 404 behavior. A rewrite should not turn every missing asset into an accidental success page unless that is deliberate.
  5. Test both the bare and www host variants. Check whether they intentionally remain separate or converge on one canonical host.
  6. Add a query string, such as ?level=hard&mode=coop, and confirm that the application receives it after the mapping or redirect.
  7. Request /public and /public/assets/site.css. They must not become /public/public or trigger repeated redirects.
  8. Repeat tests with percent-encoded characters and trailing slashes used by your application. Check the final filesystem path and the browser-visible URL, not just the status code.

For header-only checks, an HTTP client such as curl can show the first response without following it:

curl -I http://example.com/
curl -I https://example.com/games/zelda
curl -I 'https://example.com/search?q=arcade'
curl -I https://www.example.com/public/assets/site.css

Use your server’s access and error logs when the status or path is unexpected. Logs reveal which virtual host handled the request, whether the rule was processed and whether the rewritten filesystem path exists. Remove or protect any temporary diagnostic settings after testing.

Deployment and rollback checklist

  • Back up the existing root .htaccess file before editing it.
  • Confirm DNS, the document root, the physical public directory and read permissions.
  • Confirm mod_rewrite, override permissions and the Apache version’s flag support.
  • Choose internal rewriting or a visible redirect; do not combine them to solve the same URL requirement.
  • Use the fixed, allowlisted destination host in any external redirect.
  • Deploy with 302 while behavior is being verified.
  • Record the previous file so you can restore it immediately if a loop, outage or unexpected canonical URL appears.
  • After a permanent move to 301, expect cached responses and test with a cache-bypassing client when making subsequent corrections.

The essential pattern is simple: test the hostname in RewriteCond, match the relative path in RewriteRule, exclude the destination directory, and select an internal path substitution or an explicit 3xx response according to the URL visitors should see.

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

Quick Recap

Bestseller No. 2
Bestseller No. 4
Bestseller No. 5

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
PC Slower Than It Used to Be?Free scan - under a minute

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.