Using RewriteRules

software development

#1

I’m hoping this is the right place for this question.

I want to use RewriteRules for a website on DreamHost, but I’m having a great deal of trouble making them work.

I’m familiar with regular expressions but I’ve never really done RewriteRules before.

Here’s the only one I’ve been able to get working:

RewriteRule /test.html /test2.html [L,QSA]

and when I go to domainname.com/test.html I do indeed get served up “test2.html” instead.

But of course, I want something more complex than that.

I was hoping to create a simple web app whereby a URL which looks like “domainname.com/ice/cream/” gets served up by “domainname.com/cgi/script.cgi?foo=ice&bar=cream” – it must be possible, and I believe I can write a regular expression for it, but if I write just

RewriteRule /ice/cream/ /test.html

nothing happens when I go to /ice/cream/ except a 404. Where am I going wrong?

Thanks in advance,

johnh


#2

The following will do what you want:

RewriteEngine On RewriteRule ^([a-z]+)/([a-z]+) /cgi/script.cgi?foo=$1&bar=$2 [L] Don’t use a leading slash in your rule.

A good way to test is to add a R in that last bit: [L,R]. This will redirect you instead of rewriting internally. You’ll get a 404 if script.cgi doesn’t exist yet, but you’ll see your parameters in the URL line so you can verify that they’re being passed correctly.


If you want useful replies, ask smart questions.


#3

Hi, thanks for that, testing now, but, is that supposed to be a space after the character class? Not a plus?


#4

OK, I’ve done that and … the whole site, every page and every directory, is now a 500 server error.

Is it possible you could test this on a DreamHost account? And paste the whole file here for me?


#5

Right you are. This forum strips out plus signs for some reason. It’s fixed now.

Anyway, you’re also right that this doesn’t work as written. That’s what I get for drinking wine and answering technical questions at the same time. Try this:

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-z]+)/([a-z]+) /cgi/script.cgi?foo=$1&bar=$2 [L] To find the source of 500 errors, log in via SSH and check your error log:

tail logs/example.org/http/error.log Where “example.org” is your actual domain name, obviously.


If you want useful replies, ask smart questions.


#6

Thank you very much. It’s working now.

Although, as a footnote, I gave up with the foo=$1&bar=$2 and so on, it got a bit complicated both in both the RewriteRule and the script.

What I do instead is have the script it refers to split $ENV{SCRIPT_URI} on the slashes. Works just as well.

my (@array) = (
split(’/’,substr($ENV{‘SCRIPT_URL’},1))
);