Forum Moderators: phranque

Message Too Old, No Replies

Complex mod rewrite problem

         

JayWll

3:03 am on Mar 7, 2011 (gmt 0)

10+ Year Member



I'm in the process of getting to grips with mod_rewrite so I've gotten myself perilously close to what I'm trying to achieve, but I'm stuck on one detail and so I'm hoping I can get some help.

First off, here's what I have in my .htaccess file so far:
Options -Indexes 
Options +FollowSymLinks

RewriteEngine On

# Remove www
RewriteCond %{HTTP_HOST} ^www.(.*) [NC]
RewriteRule (.*) http://%1/$1 [R=301,L]

# Redirect foo.com to /foo subdirectory
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^foo.com$ [NC]
RewriteRule .* /foo%{REQUEST_URI} [QSA,L]

# Redirect bar.com to /bar subdirectory
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^bar.com$ [NC]
RewriteRule .* /bar%{REQUEST_URI} [QSA,L]


Essentially what it's doing here is invisibly rewriting the file path so that a request for [foo.com...] actually returns the file found at /foo/hello.html, and [bar.com...] returns /bar/hello.html. The server of course is set up for both and while I know that a couple of virtualhosts in the apache setup would achieve this in a much simpler way, I unfortunately don't have the luxury of being able to go that route.

So, this is all working great except for one detail: when a subdirectory is requested and the URL typed includes the trailing slash, everything is peachy... [foo.com...] returns /foo/sub/index.html and the URL in the browser's address bar remains [foo.com...]

However, if the trailing slash is omitted then things start to fall apart slightly... [foo.com...] correctly returns /foo/sub/index.html, but the URL in the browser's address bar changes to [foo.com...]

I kind of understand why this happens, but how do I change this behaviour, bearing in mind that .htaccess is the only method I have of adjusting the apache configuration?

Thanks in advance for your help!

jdMorgan

6:08 pm on Mar 9, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



See DirectorySlash: [httpd.apache.org...]

DirectorySlash off
#
Options -Indexes +FollowSymLinks -MultiViews
#
RewriteEngine on
#
# Externally redirect to remove "www" and any trailing FQDN label or port number
RewriteCond %{HTTP_HOST} ^(www\.)+([^.]+(\.[^.]+)*)\.?(:[0-9]+)?$ [NC]
RewriteRule ^(.*)$ http://%2/$1 [R=301,L]
#
# Internally rewrite specified subdomains to corresponding subdomain-subdirectory
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^(foo|bar)\.example\.com
RewriteRule ^(.*)$ /%1/$1 [L]

Alternative for RedirectStatus rewritecond:

RewriteCond $1 !^(foo|bar)/

Jim