I'm along the way of cleaning my domain's directory structure (woe be in my experience for establishing the main url's content within the root directory!) and want some insight regarding how to use RewriteRule properly.

The Gist

I would like domain.tld to make use of domain.tld/subdirectory/ but nonetheless appear as domain.tld within the url.

My .htaccess To Date

Options +FollowSymlinks
RewriteEngine On

#Force removal of wwww subdomain
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.domain.tld
RewriteRule ^(.*)$ http://domain.tld/$1 [R=301,L]

#Trailing slash
RewriteRule ^/*(.+/)?([^.]*[^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]

#Redirect root url to subdirectory
RedirectMatch 301 ^/subdirectory/$ http://domain.tld/
RewriteRule ^/$ /subdirectory/?$ [L]

The RedirectMatch is effective. Regrettably, t appears the final RewriteRule there should work simply enough, however it does not. That old content setup within the root directory still seems.

What shall we be held missing here?

Update: Resolved

Simple fix that i'm not experienced enough using the .htaccess / apache to have the ability to explain why.


RewriteRule ^/$ /subdirectory/?$ [L]

Getting rid of the rear slash fixed everything:

RewriteRule ^$ /subdirectory/?$ [L]

Now my real question is: can you explain that?

Negligence URI inside a RewriteRule does not retain the preceding slash.

To match http://example.com/ make use of RewriteRule ^$ where RewriteRule ^/$ would theoretically match http://example.com// (note double slash).

Additional: ?$ in the finish does not make sense at all, because this would give a querystring by having an empty parameter $.

Finally you've: RewriteRule ^$ /subdirectory/ [L,QSA]

Both rules are VALID:

That one for use in server configuration or virtual host context (URL begins with leading slash):

RewriteRule ^/$ /subdirectory/ [L]

Should you put the same rule in .htaccess, then you've to get rid of leading slash (since it is relative to the present folder):

RewriteRule ^$ /subdirectory/ [L]

P.S. Floern already pointed out about ?$ it target URL part. No requirement for $ whatsoever. Should you finish your URL with ? this informs Apache not to to transfer query string to new URL (drop query string completely).

Furthermore, [QSA] flag is just needed should you adjusting with query string (have ? in target URL) but still would like current query string be appended towards the recently build URL. Which means that within this rule RewriteRule ^$ /subdirectory/ [L,QSA] the [QSA] flag does nothing whatsoever and may be securely removed.