Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess rewrite to redirect root URL to subdirectory

People also ask

How can I redirect and rewrite my urls with an .htaccess file?

Use a 301 redirect . htaccess to point an entire site to a different URL on a permanent basis. This is the most common type of redirect and is useful in most situations. In this example, we are redirecting to the "example.com" domain.


You can use a rewrite rule that uses ^$ to represent the root and rewrite that to your /store directory, like this:

RewriteEngine On
RewriteRule ^$ /store [L]

I was surprised that nobody mentioned this:

RedirectMatch ^/$ /store/

Basically, it redirects the root and only the root URL. The answer originated from this link


Try this:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
RewriteRule ^$ store [L]

If you want an external redirect (which cause the visiting browser to show the redirected URL), set the R flag there as well:

RewriteRule ^$ /store [L,R=301]

Here is what I used to redirect to a subdirectory. This did it invisibly and still allows through requests that match an existing file or whatever.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?site.com$
RewriteCond %{REQUEST_URI} !^/subdir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /subdir/$1
RewriteCond %{HTTP_HOST} ^(www.)?site.com$
RewriteRule ^(/)?$ subdir/index.php [L]

Change out site.com and subdir with your values.


To set an invisible redirect from root to subfolder, You can use the following RewriteRule in /root/.htaccess :

RewriteEngine on

RewriteCond %{REQUEST_URI} !^/subfolder
RewriteRule ^(.*)$ /subfolder/$1 [NC,L]

The rule above will internally redirect the browser from :

  • http://example.com/

to

  • http://example.com/subfolder

And

  • http://example.com/foo

to

  • http://example.com/subfolder/foo

while the browser will stay on the root folder.