dimanche 5 mai 2019

Serving subdomains from directory, redirect back to user-friendly URL

I'm trying to set up .htaccess so that it would work in the following way:

1. What I want to achieve:

domain.com -> serve from ~/www/domainfolder/domain.com/, if doesn't exist then redirect serve ~/www/index.html

subdomain.domain.com -> serve from ~/www/subdomainfolder/subdomain/, if doesn't exist then redirect to domain.com

domain.com/subdomainfolder/subdomain/ -> redirect to subdomain.domain.com

domain.com/domainfolder/domain.com/ -> redirect to domain.com

I have already managed to set up some rules (www to non www, force ssl):

2. What already works:

RewriteEngine On

# www to non-www (HTTP)
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1/ [R=301,L]

# www to non-www (HTTPS)
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/ [R=301,L]


# HTTP to HTTPS
#   RewriteCond %{HTTPS} on
#   RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,QSA,L]

# HTTP to HTTPS
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,QSA,L]

# Restrict access for subdirectories
    Options -Indexes

But I'm still at large trying to set up the above-mentioned rules for substituting and redirecting subdomains. Here is the code I have experimented with so far.

3. What I'm working with

# entire domains (aliases)
    RewriteCond %{REQUEST_URI} !^domains/
    RewriteCond %{REQUEST_URI} !^/domains/
    RewriteCond %{HTTPS_HOST} ^(www\.)?(.*)$
    RewriteCond %{DOCUMENT_ROOT}/domains/%2 -d
    RewriteRule (.*) domains/%2/$1 [DPI]

# subdoms (with or without www )
    RewriteCond %{REQUEST_URI} !^subdom/
    RewriteCond %{REQUEST_URI} !^/subdom/
    RewriteCond %{HTTPS_HOST} ([^\.]*)\.([^\.]*)$
    RewriteCond %{DOCUMENT_ROOT}/subdom/%2 -d
    RewriteRule (.*) subdom/%2/$1 [DPI]

# aliases - redirect when / is missing
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^domains/[^/]+/(.+[^/])$ /$1/ [R]

# subdom - redirect when / is missing
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^subdom/[^/]+/(.+[^/])$ /$1/ [R]

RewriteCond %{HTTP_HOST} ^(www\.)?jozefmutis.com$ 
RewriteCond %{REQUEST_URI} !^/domains/jozefmutis.com/ 
RewriteRule (.*) /domains/jozefmutis.com/$1 [L] 


#RewriteCond %{HTTP_HOST} jozefmutis.com$
#RewriteCond %{REQUEST_URI} !^/subdom/www/
#RewriteRule (.*) /subdom/www/$1 [L]

Although I have not achieved what I want with this, so I'm ready to scrap it entirely for a better solution.

I specifically don't want to hard-code the domain name and would prefer it to remain dynamic




Aucun commentaire:

Enregistrer un commentaire