views:

19

answers:

2

How to rewrite /foo-bar to foo-bar.html but /foo/bar to foo--bar.html using mod_rewrite?

In other words, replace all slashes in the request URI with --, then append .html.

I wrote the following code:

RewriteEngine On
RewriteBase /

# Take care of /foo/bar and /foo-foo/bar-bar
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9-]+)/([a-z0-9-]+)/?$ $1--$2.html [L]

# Take care of /foo, or /foo-bar-baz-whatever-no-slashes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9-]+)/?$ $1.html [L]

This seems to work on some servers but on mine it seems to mess up the rewrites:

The requested URL /foo.html/bar was not found on this server.

It seems to append the .html too early.

Any ideas on how to fix this, and what is causing it to fail on this particular server?

+1  A: 
Jeremy
Weird, it seems to work without the `RewriteBase` directive. Any clue why? Thanks!
Wendy
+1  A: 

One case where this seems to happen is when MultiViews is enabled, but AcceptPathInfo is set to Off (or Default and the handler doesn't accept path info), and foo.html exists.

Apache notices that your request for /foo/bar doesn't point to a real resource, and maps it to /foo.html with the path info of /bar. Because path info is not allowed, Apache returns a 404 for the request. Likewise, mod_rewrite doesn't perform a rewrite because /foo.html now is an existing file.

The solution for this scenario would be to turn off MultiViews in your .htaccess file:

Options -MultiViews
Tim Stone