Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .htaccess to set a sub directory as root directory [closed]

Is there a way to use htaccess to tell a subdirectory to act as the root for the entire site?

For example, if I had a website under http://localhost/testsite/ and in it's index.php file I had a reference to the stylesheet using the following code..

<link rel="stylesheet" type="text/css" href="/css/layout.css" />

Could I then make that load /localhost/testsite/css/layout.css?

To get around this problem, I set up localhost subdomains for each site which although works, is not ideal.

Many thanks.

like image 337
Stibily Avatar asked Feb 23 '12 12:02

Stibily


People also ask

Does htaccess work on subdirectories?

htaccess file are applied to the directory in which the . htaccess file is found, and to all subdirectories thereof. However, it is important to also remember that there may have been . htaccess files in directories higher up.

Can I have two htaccess files?

You can have as many . htaccess levels as you want, but they're processed in order of directory tree depth. If a higher . htaccess redirects elsewhere before a lower .

What should be in htaccess file?

The . htaccess file provides a way to make configuration changes to your website on a per-directory basis. The file is created in a specific directory that contains one or more configuration directives that are applied to that directory and its subdirectories.


2 Answers

If you want to keep the 'href="/css/layout.css"' part, then yes, you can set up a rewrite rule. You just have to be careful not to redirect anything starting with /testsite (or you'll end up with a loop).

Like (in root .htaccess):

RewriteEngine On

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

There, you will be able to access your layout.css file either from:

http://localhost/testsite/css/layout.css

or

http://localhost/css/layout.css

like image 62
huelbois Avatar answered Oct 04 '22 23:10

huelbois


Sure, all relative URIs (as yours) are relative to the base URI which by default is the URI of the document:

http://localhost/testsite/index.php

You only need to tell which part to add:

<link rel="stylesheet" type="text/css" href="./css/layout.css" />
                                             ^
                                             ` see this dot

Example:

Base URI      ::  http://localhost/testsite/index.php
Relative URI  ::  ./css/layout.css
Result        ::  http://localhost/testsite/css/layout.css

If you need to have this more modular, there are multiple ways to do that. One is to set the base URI explicitly inside the HTML document (see <base>).

Another one is to resolve links relatively on the server-side based on the Request URI and your site's root-path. See this answer for an example.

like image 34
hakre Avatar answered Oct 04 '22 22:10

hakre