Mod_rewrite misbehaving?


#1

Hi,
I’m trying to redirect requests like http://my.domain/ as follows:

http://my.domain/ -> http://my.domain/sputnik.cgi?p=
http://my.domain/xx -> http://my.domain/sputnik.cgi?p=xx

I have .htaccess properly setup, but the rewrite rules are doing some funny things that I can’t seem to match up with what the specification says. For example, it’s mapping:

http://my.domain/ -> http://my.domain/sputnik.cgi?p=sputnik.cgi
http://my.domain/xx -> http://my.domain/sputnik.cgi?p=sputnik.cgi

Here’s my .htaccess:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)$ sputnik.cgi?$1 [L]

From what I understand, ^(.*)$ will match the entire request and store it in $1. If so, then why does $1 always contain sptunik.cgi?


#2

My guess is that it’s trying to re-rewrite http://my.domain/sputnik.cgi?p=xx and coming up with http://my.domain/sputnik.cgi?p=sputnik.cgi.

Try this:

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ sputnik.cgi?$1 [L,QSA]

This specifically forbids Apache from rewriting any URL that refers to an actual file (like sputnik.cgi) or directory. The extra “QSA” flag makes parameters passed to the original URL get tagged onto the rewritten URL, so (for instance) http://my.domain/xx?y=z gets turned into http://my.domain/sputnik.cgi?xx&y=z


#3

You suggestion almost works like this:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^$ sputnik.cgi?p=
RewriteRule ^(.*)$ sputnik.cgi?p=$1 [L]

Except requests that already have sputnik.cgi? fail:
http://my.domain/sputnik.cgi?p=icons/sputnik.png

because it matches sputnik.cgi?p=icons/sputnik.png. Instead if there’s a sputnik.cgi in the request, I don’t want to rewrite. but adding something like RewriteCond %{REQUEST_FILENAME} !.?sputnik.cgi. doesn’t help.

thanks!


#4

ahhh. This seems to work just fine:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !.?sputnik.cgi.

RewriteRule ^$ sputnik.cgi?p=
RewriteRule ^sputnik.cgi(.)$ sputnik.cgi$1 [L]
RewriteRule ^(.
)$ sputnik.cgi?p=$1 [L]


#5

Hmm, that seems a little more complicated than it should have to be. If it’s working for you, though… shrug good enough!