Unapedra
Unapedra

Reputation: 2373

.htaccess makes subdirectory appear in URL

I've been searching for this but I'm really newbie with .htacces (I find it a hell) and I cannot get the way to solve this.

I have the root folder in my server, redirecting the default domain URL to the folder "web". I have another folder, let's say subfold, and inside this, I have another folder: mobile.

What I want is that if someone types www.adomain.com it goes to root/subfold, without showing the subfold. I've done it this way:

RewriteEngine on
Options +FollowSymLinks
RewriteBase /

RewriteCond %{HTTP_HOST} ^www\.adomain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/subfold/ [NC]
RewriteRule (.*)$ /subfold/$1 [L]

RewriteCond %{HTTP_HOST} www\.maindomain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/web/ [NC]
RewriteRule (.*)$ /web/$1 [L]

However, when I go to www.adomain.com/mobile it shows in the URL www.adomain.com/subfold/mobile/

My aim is that if I go to the mobile subfolder, in the URL it should show www.adomain.com/mobile

Obviously, I would like not to have to write a redirect everytime I add a subfolder, it it was possible.

How should I do that?

Thanks for your time and help!

Upvotes: 1

Views: 87

Answers (1)

Jon Lin
Jon Lin

Reputation: 143876

You're getting redirected because your accessing a directory without a trailing slash. The mod_dir module, on by default, will redirect the browser and add a trailing slash if someone tries to access a directory without a trailing slash. This is because there is a information disclosure issue with indexing directories. You can either turn this off:

DirectorySlash Off

and risk having the contents of your directories get listed, even if there's an index.html file. Or add a bunch of rules to ensure there's a trailing slash:

RewriteEngine on
Options +FollowSymLinks
RewriteBase /

# redirect for trailing slash:
RewriteCond %{HTTP_HOST} ^www\.adomain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/subfold/ [NC]
RewriteCond %{DOCUMENT_ROOT}/subfold%{REQUEST_URI} -d
RewriteRule (.*[^/])$ /$1/ [L,R=301]

RewriteCond %{HTTP_HOST} ^www\.adomain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/subfold/ [NC]
RewriteRule (.*)$ /subfold/$1 [L]

# redirect for trailing slash
RewriteCond %{HTTP_HOST} www\.maindomain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/web/ [NC]
RewriteCond %{DOCUMENT_ROOT}/web%{REQUEST_URI} -d
RewriteRule (.*[^/])$ /$1/ [L,R=301]

RewriteCond %{HTTP_HOST} www\.maindomain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/web/ [NC]
RewriteRule (.*)$ /web/$1 [L]

Upvotes: 2

Related Questions