mod_rewrite Redirect Rule Variables question
-
06-07-2019 - |
Question
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.
Solution
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
OTHER TIPS
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