9

I'm wanting to take a URL such as http://localhost/universe/networks/o2/o2_logo.gif and do the following:

If it begins with /universe/
Strip /universe/ from it to become /networks/o2/o2_logo.gif
Check if this exists in %{DOCUMENT_ROOT}/networks/o2/o2_logo.gif
If so, silently rewrite the request to this file.

If I use a rule of:

RewriteCond %{REQUEST_URI} ^/universe/
RewriteRule ^(.*)$ http://www.example.org/$1 [L]

http://localhost/universe/networks/o2/o2_logo.gif gets re-written to http://www.example.org/networks/o2/o2_logo.gif which is great, but I can't seem to use the

How can I go about using this 'changed' %{REQUEST_URI} further down as say $1 or something?

Gumbo
  • 643,351
  • 109
  • 780
  • 844
Alistair
  • 1,326
  • 1
  • 8
  • 17

2 Answers2

17

I was not able to get this right purely with .htaccess but used the following file:

RewriteEngine On

# Does the file exist in the content folder?
RewriteCond %{REQUEST_URI} !^/content.*
RewriteCond %{DOCUMENT_ROOT}/universe/%{REQUEST_URI} -f

# File Exists
RewriteRule ^ %{DOCUMENT_ROOT}/universe/%{REQUEST_URI} [L]

# If the request is not a file, link or directory then send to index.php
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L] # Item exists so don't rewrite

# Nothing exists for the request so append a trailing / if needed
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^ %{REQUEST_URI}/ [R=301,L]

RewriteRule ^.*$ index.php [NC,L] # Send off as-is to index.php

Then I went into my document_root folder and did the following:

cd /var/www/journal
ln -s journal/public universe
cd /var/www/journal/public
ln -s content/ universe

That combined with the htaccess meant everything was working.

Alistair
  • 1,326
  • 1
  • 8
  • 17
  • This is a wonderful answer. I tried several other peoples' ideas and then discovered this. Man ... htaccess is one hell of a config file ... – MikeMurko May 03 '14 at 14:49
  • what is 'content folder' here? There is no content folder mentioned in the question. Confused. – jamacoe Sep 09 '22 at 14:50
1

Try this rule:

RewriteCond %{DOCUMENT_ROOT}$1 -f
RewriteRule ^universe/(.*) $1 [L]
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • Looks like it's heading in the right direction. My .htaccess contains this: # Does the entry exist in the content folder? RewriteCond %{DOCUMENT_ROOT}/universe/public/content/$1 -f RewriteRule ^universe/(.*) http://localhost:81/exists/$1 [L] RewriteRule ^universe/(.*) http://localhost:81/not_exists/$1 [L] Still generates a 404 though when I'd expect it to follow one of the two RewriteRules at least? What could I be missing for it to ignore this? Content is in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\universe\public\content – Alistair May 16 '09 at 19:24
  • Oh, so you want to pass it through to a server in the local network. Then you need to use a proxy. Just add the P flag to the rules. – Gumbo May 16 '09 at 20:05