Reputation: 18184
I am trying to make a subdomain forward through the htaccess document. The below instructions will forward http://sub.domain.com
to the internal structure Root > subfolder > index.php
. This all works well.
# REWRITE DEFAULTS
# ====================================================================================================
RewriteEngine On
RewriteBase /
# SUBDOMAIN FORWARD
# ====================================================================================================
RewriteCond %{HTTP_HOST} ^sub.domain.com$
RewriteRule ^(/)?$ subfolder/index.php [L]
RewriteCond %{HTTP_HOST} ^sub.domain.com$
RewriteCond %{REQUEST_URI} !^/subfolder/
RewriteRule ^(.*)$ /subfolder/$1
There is only one (big) downfall with this method. When you try to reach a folder within the subfolder such as Root > subfolder > images
by going to http://sub.domain.com/images/
then all works well again, however when you don't end it with a slash http://sub.domain.com/images
the url in the address bar will become http://sub.domain.com/subfolder/images/
which is clearly not what I want.
So what if I would add a slash if a slash was forgotten?
RewriteCond %{HTTP_HOST} ^(.*).domain.com$
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteCond %{REQUEST_FILENAME} !(.*)/$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ http://%1.domain.com/$1/ [L,R=301]
This all works when you have a normal URL (http://www.domain.com/images
), because it will detect it is a directory and adds a slash and if it's a file it will omit the slash. However this does not work for our http://sub.domain.com/images
example.
Does anyone have an idea how you can make subdomains work properly using htaccess?
Upvotes: 2
Views: 572
Reputation: 784878
That is happening because /subfolder/images
is a real directory and mod_dir
module adds a trailing slash to all directories by doing a 301 redirect.
You can use it like this:
RewriteEngine On
# add a trailing slash if /subfolder/images is a directory
RewriteCond %{HTTP_HOST} ^sub\.domain\.com$ [NC]
RewriteCond %{DOCUMENT_ROOT}/subfolder/$1/ -d
RewriteRule ^(.*?[^/])$ %{REQUEST_URI}/ [L,NE,R=302]
RewriteCond %{HTTP_HOST} ^sub\.domain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/subfolder/
RewriteRule ^(.*)$ /subfolder/$1 [L]
Upvotes: 1