Use regular expressions in .htaccess for redirections

Task one:

Apache server provides a .htaccess file using which you can use to redirect URLs. For example, if you want to redirect all visitors to http://dallascao.com/cn/ to http://dallascao.com/en/, you can open the .htaccess file at the root, and then input:

RewriteRule ^cn\/?$ en\/

Translating the code in English, it means “Please replace ‘^cn\/?$’ with ‘en/’”. “^cn\/?$” is a regular expression, in which:

“^” matches the beginning of a string.
“$” matches the end.
“\” means “/” following it stands for “/” itself, not part of the grammar.
“?” means there can be one “/” or no “/”

So “^cn\/?$” matches two strings: “cn/” or “cn”. When visitors visit http://dallascao.com/cn/ (end with a slash) or http://dallascao.com/cn (end with no slash), they are redirected to http://dallascao.com/en/

Task two:

If you want to redirect all visitors to the root of http://dallascao.com/ to http://dallascao.com/en/, I can use this:

RewriteRule ^$ en\/

“^$” matches an empty string, meaning the root.

Task three:

Inputting the following code into the .htaccess of http://gt4t.net/, all visitors to http://gt4t.net/anything/ to http://gt4t.net/en/anything/. For example, visitors to http://gt4t.net/downloads/ will be redirected to http://gt4t.net/en/downloads.

RewriteRule ^(.*?)\/?$ \/en\/$1

“^(.*?)\/?$” means anything that either ends with one “/” or no “/”. In the second part, “\/en\/$1″, “$1″ stands for the 1st bracketed element in the previous string “^(.*?)\/?$” (in this case, the only bracketed element.). And it means replacing “ANYTHING” ending with “/” or no “/” with “/en/ANYTHING/”

By the way, if you want your redirection to be hidden, you can add the following option to the beginng .

Options +FollowSymLinks

In the example above, your visitors to http://gt4t.net/downloads is redirected to http://gt4t.net/gt4t_en/downloads/ but http://gt4t.net/downloads is still shown in the address bar.

Finally, here is is the complete .htaccess file:

RewriteEngine on
Options +FollowSymLinks
 
RewriteCond %{HTTP_HOST} ^gt4t.net$ [OR]
RewriteCond %{HTTP_HOST} ^www.gt4t.net$
RewriteRule ^(.*?)\/?$ \/gt4t_en\/$1 [L]

Confused? Contact me if you have such a need. I will be happy to help you.

Share

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Leave a Reply