tags:

views:

19

answers:

2

I would like to rewrite /anything.anyextension into /?post=anything.

eg:

  • /this-is-a-post.php into /?post=this-is-a-post or
  • /this-is-a-post.html into /?post=this-is-a-post or even
  • /this-is-a-post/ into /?post=this-is-a-post

I tried

RewriteRule ^([a-zA-Z0-9_-]+)(|/|\.[a-z]{3,4})$ ?$1 [L]

but it doesn't work.

Any help appreciated.

A: 

If you have access to the main server configuration, use this:

RewriteRule ^/(.+)\.\w+$ /?post=\1 [L]

If not, and you are forced to put this in a .htaccess file, you could try

RewriteRule ^(.+)\.\w+$ /?post=\1 [L]

In either case, this assumes you will only be rewriting URLs with a single path component (i.e. if you get a request like /path/anything.anyextension it might not work as you expect, the rewrite rule would need to be modified to handle that)

David Zaslavsky
This will fail to catch any entry without extensions
Ast Derek
@Ast: yes, that is the desired behavior.
David Zaslavsky
A: 

You need a better way to determine when to apply the rewrite rule, otherwise your page won't be able to display external JS or CSS, unless you define an exception.

SilverStripe (or the core, Sapphire) offers a good approach to this, something like:

RewriteEngine On
RewriteCond %{REQUEST_URI} !(\.css)|(\.js)|(\.swf)$ [NC]
RewriteCond %{REQUEST_URI} .+
RewriteRule ^([^\.]+) /?post=$1 [L,R=301]

This requires the URI not to be empty, not to be JS, CSS or SWF, and redirects back to your root directory:

http://localhost/this-is-a-post.php
http://localhost/?post=this-is-a-post

If you don't want a redirection, but the processing, remove the redirection rule R=301

Ast Derek