views:

230

answers:

2

I would like to take requests for /somefolder/style.css and handle them with /somefolder/program.php

So, I put the following in my .htaccess file:

rewriteengine on
rewriterule ^style.css$ program.php?css=1 [R=302,L]

The result is that instead of redirecting to /somefolder/program.php, the server tries to redirect to:

/var/www/html/somefolder/program.php?css=1

How can I get rid of the /var/www/html/ in the redirect? I thought that since I just entered program.php in the .htaccess that it would default to the same folder.

Since this is a generic script that I will use in many places, I would like to avoid using rewritebase to specify the folder I'm in -- the .htaccess has to work in any folder without being modified.

+6  A: 

Leave the R flag away and you will get an internal redirect:

RewriteRule ^style\.css$ program.php?css=1 [L]

Otherwise specify the full URL path you want to redirect to externally:

RewriteRule ^style\.css$ /program.php?css=1 [R=302,L]

Or for any arbitrary folder:

RewriteCond %{REQUEST_URI} (.*)/style\.css$
RewriteRule ^style\.css$ %1/program.php?css=1 [R=302,L]
Gumbo
Excellent! I had no idea that the R had that effect.
Andrew Swift
God, I feel stupid for forgetting about needing the R for a web redirect...
Kevin Peno
A: 

I think the problem is that you are missing a ReWrite base statement.

Also the I would put the .htaccess file in the root directory of your site. That way you don't have to copy an .htacess file into every new directory you create. What if you want to change the name of your php file? You'd have to change every .htaccess file.

This is how I would redirect www.mydomain.com/orange/style.css to www.mydomain.com/orange/program.php?css=1 using generic rules:

RewriteEngine On
RewriteBase /
RewriteRule  ^(.*)/style\.css$ $1/program.php?css=1 [L]
jeph perro
jeph perro, OP says "I would like to avoid using rewritebase to specify the folder I'm in -- the .htaccess has to work in any folder without being modified."
bmb
I disagree with that approach and I explained my reasons. Why have multiple .htaccess files all over the place? Just have one at the root and control everything from there.
jeph perro
The reason is because in some of the sites I will be using this on, there is ALREADY an htaccess file that handles rewrites differently for other parts of the site. In this case I need a modular solution that I can drop in to an existing environment without affecting the existing redirects. I agree that all things being equal, it would be better to have a single htaccess file.
Andrew Swift