Mod Rewrite Tutorial
Before do rewrite you should turn on the rewrite module, using following syntax:
RewriteEngine On
General structure of mod rewrite is like following:
RewriteRule Pattern Substitution [OptionalFlags]
RewriteRule: RewriteRule is the command to rewrite the following conditions.
Pattern: It is the pattern of request. The pattern is using regular expression (regex) syntax.
Substitution: Subtition is the target URL where it will be redirected.
OptionalFlags:
Some useful optional flags includes:
- F - Forbidden. The user will receive a 403 error.
- L - Last Rule. No more rules will be proccessed if this one was successful.
- R[=code] - Redirect. User will be redirected to substitution URL.
Mod Rewrite Examples
Basic redirection from old_page.html to new_page.html
RewriteRule ^old_page\.html$ new_page.html [L]
Redirect from page-1.hml to page.php?id=1
RewriteRule ^page-([^-]*).html$ /index.php?id=$1 [L]
Redirect from /health/6.html to detail.php?category=health&id=6
RewriteRule ^([^/]*)/([^/]*)\.html$ /detail.php?category=$1&id=$2 [L]
Redirect from /news-detail-500.html to news.php?type=detail&news_id=500
RewriteRule ^news-([^-]*)-([^-]*)\.html$ /news.php?type=$1&news_id=$2 [L]
Create directory shortcut
RewriteRule ^/shortcut$ /very/long/directory/
Prevent Hot Linking
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com/ [NC]
RewriteRule \.(gif|jpg|png)$ - [F]
or show hotlinked notice error
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com/.*$ [NC]
RewriteRule \.(gif|jpg|png)$ http://www.yourdomain.com/warning_hotlinked.gif [R=301,L]
Move to another web server / domain
RewriteEngine on
RewriteRule ^/~(.+) http://www.newdomain.com/~$1 [R,L]
Redirecting non existing directory or page
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .? /404.php [L]
Create Permanent 301 Redirection
RewriteRule ^old_page\.html /new_page.html [R=301,L]
Block Search Engine Bot
RewriteCond %{HTTP_USER_AGENT} Google [OR]
RewriteCond %{HTTP_USER_AGENT} Yahoo [OR]
RewriteRule .* - [F]
Redirect to maintenance page
RedirectMatch 302 ^/ /maintenancepage.html
Redirect any broken image to default image
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^images/.*\.jpg$ /images/default.jpg [L]
Block Specific IP Address
RewriteCond %{REMOTE_ADDR} ^(8\.8\.8\.8)$ [OR]
RewriteCond %{REMOTE_ADDR} ^(101\.103\.104\.105)$ [OR]
RewriteRule ^/* http://www.yourdomain.com/blocked.html [L]