5 Most Useful Regular Expressions & Rewrite Rules

Written by Mostafa Dafer on . Posted in Tips & Tricks

I’ve been working lately on a project that uses silent redirection. I noticed that most users lack the basics of this great language! To start with, Regex (or Regular Expression)  is a sequence of characters that forms a search pattern; that’s the main reason Regex was created for. So I thought like sharing with you 5 of the most useful tips of Regex. As a quick introduction, regex can be used in various search forms, it’s main value lies in the fact that it’s advanced enough to automate most automated “Find and Replace” tasks. One reason to use Regex is setting up silent redirects on Apache servers (like silently redirecting subdomain.example.com to example.com/ugly/url/test.php?redirect=subdomain). Wondering why we may want to set up such silent redirects? You may be unaware of the fact that a huge number of the websites you visit everyday use silent redirects. One reason is allowing users to create dynamic subdomains; like allowing registered users to create their own subdomains without changing any dns records. Note: I will be using Regex in writing .htaccess redirect rules, if you would like to know more about redirect rules try this post by addedbytes. So here we go with the first tip:

1- This code silently redirects http://example.com/pet-care to http://example.com/pet_care_info_ugly_url.php without the user noticing it!

RewriteRule    ^pet-care/?$    pet_care_info_01_02_2008.php    [NC,L]
  2- A “.” means any character, so the following example replaces user1 as well as userX to users.php:
RewriteRule    ^user.$    users.php    [NC,L]
  3- A “*” means any number of characters. So combining . with * results in .* replacing hellonomatterwhat to matter.php in the following example:
RewriteRule    ^.*matterwhat$    matter.php    [NC,L]
4- A “\” is an escape character, so combining \ with . resulting in \. simply means the character “dot” instead of meaning “slash any character” as in the following example which removes the www from the beginning of a URL:
RewriteRule    ^www\.subdomain$    subdomain    [NC,L]
5- Merging RewriteCond with RewriteRule, resulting in changing the position of a substring is done as shown in the following example:
RewriteCond %{HTTP_HOST} !^www\.mipmart\.com
RewriteCond %{HTTP_HOST} ^(.*\.)?([a-z0-9][a-z0-9_\-]*[a-z0-9])\.mipmart\.com
RewriteCond %{QUERY_STRING} !&?shop=[^&]+
RewriteRule .* wildcard/redirect.php?shop=%2 [L]

Mostafa Dafer

Computer & Communication Eng. Stdnt. Founder & CEO of CoolesTech Knows Arabic; English, learning French, Chinese, and Japanese About me: steve.coolestech.com

Leave a comment