Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess: Redirect root url to subdirectory, but retain root url

I am in the process of cleaning up my domain's directory structure (woe be to me for setting up the root url's content in the root directory!) and need some insight on how to use RewriteRule correctly.

The Gist

I want domain.tld to use domain.tld/subdirectory/ but still appear as domain.tld in the url.

My .htaccess So Far

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 works great. Unfortunately, t seems the last RewriteRule there should work simply enough, but it doesn't. The old content setup in the root directory still appears.

What am I missing here?

Update: Resolved

Simple fix that I am not experienced enough with the .htaccess / apache to be able to explain why.

I had:

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

Removing the one slash fixed everything:

RewriteRule ^$ /subdirectory/?$ [L]

So now my question is: why is that?

like image 678
Will Phillips Avatar asked Jul 21 '11 10:07

Will Phillips


1 Answers

Try this:

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} !^/subdirectory/

# REWRITES ALL URLS 
# [REPLACE "domain" WITH THE ACTUAL DOMAIN, 
# WITHOUT THE TLD (.com, .net, .biz, etc)]
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.

# REWRITE ALL THOSE TO subdirectory
RewriteRule ^(.*)$ /subdirectory/$1 [L]

BR Spiros

like image 71
Spiros Avatar answered Sep 28 '22 05:09

Spiros