Search code examples
.htaccessmod-rewritehttp-status-code-301

Mod_rewrite, 301s and slashes


I want to set up a pretty url on a virtual directory. But I also want a safety net for the virtual directory just in case anyone hits that directly. Let's call the virtual directory foo

RewriteRule ^foo/(.*)$ ./foo/page.php?term=$1 [QSA]

This seems to be working fine. All pages are re-directing and displaying correctly and the pretty URL is remaining in the address bar (rather than re-directing to the physical address as with a 301)

But if I go to www.domain.com/foo I get a 404 :(

If I go to www.domain.com/foo/ (note the slash) then the script continues and an error message is displayed thanks to some extra validation in my PHP.

How can I tidy up the virtual directory (with/without a slash)? No one should ever hit that but if they do I want to be ready and re-direct them to the homepage.

After reading another users question I tried:

Redirect 301 /foo /?q=empty

But this is conflicting with my initial rule. I'm ending up with links like: www.domain.com/?q=empty/Blah (instead of /foo/Blah)


Solution

  • Try this:

    RewriteCond %{REQUEST_URI} ^foo/$ 
    RewriteRule ^  /foo/page.php?q=empty [L,QSA]
    
    RewriteRule ^foo/(.*)$ foo/page.php?term=$1 [L,QSA]