views:

44

answers:

2

I'm a bit of an .htaccess n00b, and can't for the life of me get a handle of regular expressions.

I have the following piece of RewriteRule code that works just fine:

RewriteRule ^logo/?$ /pages/logo.html

Basically, it takes /pages/logo.html and makes it /logo.

Is there a way for me to generalize that code with variables, so that it works automatically without having to have an independent line for each page?

I know $1 can work as a variable, but thats usually for queries, and I can't get it to work in this instance.

+1  A: 

Try this:

RewriteRule ^/pages/(.*)\.html$ /$1

The (.*) matches anything between pages/ and .html. Whatever it matches is used in $1. So, /pages/logo.html becomes /logo, and /pages/subdir/other_page.html would become /subdir/other_page

Doug Hays
+1  A: 

First you need to know that mod_rewrite can only handle requests to the server. So you would need to request /logo to have it rewritten to /pages/logo.html. And that’s what the rule does, it rewrites requests with the URL path /logo internally to /pages/logo.html and not vice versa.

If you now want to use portions of the matched string, you need to use groups to group them ( (expr)) that you then can reference to with $n. In your case the pattern [^/] will be suitable that describes any character other than the slash /:

RewriteRule ^([^/]+)$ /pages/$1.html
Gumbo
The only thing I struggled with was getting it so that it didn't apply to the php files on my server, which weren't subject to this rewrite. I ended up going with RewriteCond %{REQUEST_FILENAME} !^.*\.php$
yc
You could also use `RewriteCond %{REQUEST_FILENAME} !-f` to exclude any existing regular file.
Gumbo