apache.htaccesshttp-redirectmod-rewritemasking

htaccess rewrite to subfolder not masking


I want to redirect https://example.com/folder to https://example.com/otherfolder/anotherfolder but have the address bar still display https://example.com/folder.

None of the .htaccess tutorials on doing this work, and the only ones I can find on StackOverflow are much more complicated problems.

So far I have tried:

RewriteEngine On
RewriteRule ^folder/?$ /otherfolder/anotherfolder

I get a rewrite/redirect but the URL is not masked.

Edit: Solved, see below. Missing trailing slash.


Solution

  • RewriteRule ^folder/?$ /otherfolder/anotherfolder
    

    I assume /otherfolder/anotherfolder must be a physical filesystem directory (from the name "folder" and the fact there wouldn't ordinarily be a way to route the request otherwise). In which case you are missing a trailing slash on the substitution string (target URL).

    Without the trailing slash, mod_dir will trigger an external 301 redirect to append the trailing slash and expose the rewritten filesystem directory so you will ultimately see an external redirect to /otherfolder/anotherfolder/ (note the trailing slash).

    Note that this would be a 301 (permanent) redirect and cached persistently by the browser.

    So, the rule should be written like this instead, with a trailing slash:

    RewriteRule ^folder/?$ /otherfolder/anotherfolder/ [L]
    

    You will likely need the L (or END) flag if you have other directives.