regex - PHP .htaccess removing .php extension and language directory to parameter -
i'm looking regulair expression .htaccess
file inside php server.
what want detects language first directory parameter:
- nl
- en
- be
- de
any other options must treated directory or filename. language must given parameter without corrupting other parameters.
also want last /
replaced .php
.
some examples:
host.com/nl/index/ -> host.com/index.php?lang=nl host.com/de/test/abc/ -> host.com/test/abc.php?lang=de host.com/be/a/b/c/?t=23 -> host.com/a/b/c.php?lang=be&t=23
is possible? can't work, hope me out!
<ifmodule mod_rewrite.c> rewriteengine on rewritecond %{request_filename} !-f rewritecond %{request_filename}.php -f rewriterule >>> requested expression , replacing pattern <<< </ifmodule>
rewriterule ^/([a-z]{2})(/.+)/?$ $2.php?lang=$1 [qsa]
regexes easiest interpret considering piece @ time. let's break down:
^
- start of url/
- match first slash([a-z]{2})
- match , capture 2 letters (goes$1
variable)(
- begin capture group (goes$2
)/
- match slash.+
- match 0 or more characters)
- end capture group ($2
)/?
- match optional end slash of "file path" (but don't capture it)$
- end of url
so, you're capturing 2 things:
1. language (capture group $1
):
([a-z]{2})
2. file path, starting slash (capture group $2
), followed optional slash:
(/.+)/?
finally, qsa
flag @ end appends original query string (if there one) rewritten url. if you'd make regex match case-insensitive (i.e. allow urls host.com/nl/index/
), can add nc
flag too: [qsa,nc]
. alternatively, explicitly allow capital letters using [a-za-z]
instead of [a-z]
in regex.
Comments
Post a Comment