Use htaccess to remove any sub directories in URL

I run an Expression Engine site that will load an article page regardless of any made up sub directory names typed into the address bar.

For example all these addresses:

Will load:

Obviously, this is less than ideal for SEO since I’ve got a potentially unlimited number of duplicate URLs.

I am trying to figure out how to use htaccess to strip anything before and replace it with just www.

Any help would be appreciated!

I think this should do what you want:

RewriteCond %{http_host} ^(.+)\ [nc]
RewriteRule ^(.*)$$1 [R=301,L]
1 Like

Thanks for the suggestion. Unfortunately this seems to result in a redirect loop. Any other ideas?

Try HTTP_HOST rather than http_host - I’m not sure if it’s case-sensitive or not, but the docs seem to always show it in uppercase.

Try RewriteCond %{http_host} ! ^www\.example\.com [nc] instead :slight_smile:

1 Like

Doh, looking at it now it seems obvious that it’s going to get stuck in a loop because of the 301 redirect! :blush:

I take it the mod_rewrite variables aren’t case sensitive then?

TBH I don’t know, I just copy pasted what you had and modified the domain part. If the rule still doesn’t work I’d suggest using caps instead. :wink:


Really simple:

[code]# .htaccess in DocumentRoot

RewriteEngine on

RewriteCond %{HTTP_HOST} ! [NC]
RewriteRule .?{REQUEST_URI}[/code]

That looks at the {HTTP_HOST} and, if NOT (no case - {HTTP_HOST} is NOT case sensitive), redirects the request to

Be sure to put this before any other mod_rewrite code.

Fret: don’t use mod_alias.

Scallio got it correct.



I appreciate all the help on this so far. Still no solution as yet.

When I try Scallio’s advice:

RewriteCond %{http_host} ! ^www\.example\.com [nc]
RewriteRule ^(.*)$$1 [R=301,L]

I get a 500 Internal Server Error.

When I try dklynn’s advice:

RewriteCond %{HTTP_HOST} !www\.example\.com [NC]
RewriteRule .?{REQUEST_URI}

I get a ‘302 Found’ page that says:


The document has moved here.

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

The word ‘here’ is hyperlinked to the same error URL typed into the browser, for example

Any other tips?!

Oh I see I have a space there that shouldn’t be there.

How about

RewriteCond %{HTTP_HOST} !^www\.example\.com$ [nc]
RewriteRule .?{REQUEST_URI} [L,R=301]

Which is pretty much the best of both worlds of mine and @dklynn 's solutions :slight_smile: