301 redirect from mod_rewrite RewriteMap program

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?

Upvotes: 1

Views: 1265

Answers (2)

Cheeso
Cheeso

Reputation: 192577

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.

Upvotes: 1

Gumbo
Gumbo

Reputation: 655479

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]

Upvotes: 0

Related Questions