hogsolo
hogsolo

Reputation: 14445

Apache htaccess to rewrite up one directory level

I've seen this asked before and people provide answers, but none of them seem to work. I'm trying to rewrite the URL so any request to /whatever show as /. I don't want the location of the files to change, just the URL. For example, if someone types in:

Http://www.mysite.com/whatever ( the files are located at /docroot/whatever )
I want the URL to show http://www.mysite.com/

In my htaccess ( placed in /docroot , not /docroot/whatever ) I'm currently using:

RewriteEngine on
RewriteRule   ^whatever/(.+)$   /$1 [L]

What's happening is the URL is staying , but the server is looking for the files /docroot .

That's the opposite of what I need, I need the URL to be , with the server looking for the files in /docroot/whatever .

Upvotes: 2

Views: 2916

Answers (2)

Jon Lin
Jon Lin

Reputation: 143856

Try putting this in the htaccess file in your document root:

RewriteEngine On

# change the browser's URL address bar
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /whatever($|\ )
RewriteRule ^whatever / [L,R=301]

# internally rewrite / back to whatever
RewriteRule ^$ /whatever [L]

Upvotes: 0

TerryE
TerryE

Reputation: 10878

I think that you have it backwards.

  • If you want the root URIs to be mapped to DOCROOT/whatever then you need to do an internal redirect in Apache.
  • If you receive an external request for http://www.mysite.com/whatever and want the client to use the root URI then you need to do an external (301) redirect.
  • You also need to make sure that you don't end up in an infinite loop.

The following lines will do this for you:

RewriteEngine On
RewriteBase   /

RewriteCond   %{ENV:REDIRECT_END}  !^1 
RewriteRule   ^whatever/(.+)$  $1               [R=301,L]

RewriteCond   %{REQUEST_URI}   !^/whatever
RewriteRule   ^(.+)$           whatever/$1      [E=END:1,L]

In the second rule, the E=END:1 sets the env variable END to 1, and after the internal redirect, this becomes REDIRECT_END. The first cond stops, say /fred -> /whatever/fred -> (301) /fred -- which will cause the browser to barf.

Also start with 302s and when you've got the rules working switch to 301s -- since the client browser will cache 301s which makes a bugger of debugging these rules.

Upvotes: 1

Related Questions