views:

323

answers:

2

I'm using mod_rewrite's RewriteMap directive to process URLs. My RewriteMap program is a PHP script and everything is running fine. I'm able to map friendly URLs to PHP program + ID. Anyway, what I want to do is return a 301 redirect for certain URLs. For example, if someone puts in the URL:

http://www.example.com/directory1

Then I want my RewriteMap program to send a 301 redirect to

http://www.example.com/directory1/ (trailing slash)

Which will then go into my program again to be mapped onto a PHP script. I tried adding [R=301] at the end of my statement, but this just hangs the request. Here's the basic logic of my script:

if ($input_url == "/directory1") {
    echo "/directory1/ [R=301]\n";          // this doesn't work... just hangs
}
else if ($input_url == "/directory1/") {
    echo "/myprogram.php?id=1\n";
}

Any ideas?

A: 

That’s not possible the way you want to do it. But you could use an additional rule to redirect all requests of URLs without a trailing slash:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .*[^/]$ %{REQUEST_URI}/ [L,R=301]
Gumbo
That is what I ended up finding out -- however in my case that is not an option because sometimes it could be a directory name or sometimes it could be options passed. For example:http://www.example.com/dir1/subdirshould 301 to: http://www.example.com/dir1/subdir/but http://www.example.com/dir1/page2.htmlshould not be 301'd -- just rewritten according to rules i have setup.I guess I could modify the Rewrite Condition to look for any question that doesn't end in .html, but I want it to be flexible for any kind of string that's sent.
Sridhar
@Sridhar: Yes, that is probably the best solution. But you could also use the map to see if the same request with a trailing slash would be accepted and then do the redirect: `RewriteCond %{mymap:$0/} !^$ RewriteRule .*[^/]$ %{REQUEST_URI}/ [L,R=301]`.
Gumbo
+1  A: 

The -d test in RewriteCond is designed specifically for your case Sridhar. It tests if there is a directory present in the filesystem. If true, AND if there is no trailing slash, then you could apply the redirect. That would be like this:

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .*[^/]$ %{REQUEST_URI}/ [L,R=301]

You wouldn't need a RewriteMap (prg) in this case.

Cheeso