Search code examples
apache.htaccessmod-rewriteurl-rewritingmod-proxy

New to .htaccess and RewriteRule


I'm making a site where users can create subdomains with files, folders etc. these sites go into a folder called websites so it will be

site.com/websites/subdomain.site.com

I only need to get {REQUEST_URI} at the end of the RewriteRule so that a user can go to example, subdomain.site.com/images/etc/img.jpg and still their subdomain will be shown like subdomain.site.com/images/etc/img.jpg but the content will actually be on site.com/websites/subdomain.site.com/images/etc/img.jpg

Sorry for creating multiple questions, the docs is hard for me i'm totally new to this but im trying... please help with this :)

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} !^/websites/
RewriteCond %{HTTP_HOST} (.*)$ [NC]
RewriteRule ^(.*)$ /websites/%1/ [L]
ErrorDocument 404 /

Solution

  • Your .htaccess is quite close to what you want. You just need to use $1 as well as shown:

    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_URI} !^/websites/
    RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
    RewriteRule ^(.*)$ /websites/%1/$1 [L]
    ErrorDocument 404 /
    

    %1 only refers to the domain matched in RewriteCond.
    $1 is required to refer the rest of the URL matched in ReqwriteRule.

    EDIT: To exclude www. and site.com

    RewriteEngine on
    RewriteBase /
    RewriteCond %{HTTP_HOST} !^(www\.)?(site\.com)$ [NC]
    RewriteCond %{REQUEST_URI} !^/websites/
    RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
    RewriteRule ^(.*)$ /websites/%1/$1 [L]
    ErrorDocument 404 /