Mod_rewrite is an Apache-based rewrite engine for dynamically rewriting URLs. It’s built into Apache servers natively, though not enabled by default.
It’s capable of functions beyond simple rewrites, though, some of which are included below.
Turn Mod_Rewrite On
Mod_rewrite is used through your .htaccess file. Place the following code at the beginning of your .htaccess file to turn mod_rewrite on:
RewriteEngine on
The Basic Mod_Rewrite Layout
The basic format for a mod_rewrite command is:
RewriteRule Pattern Substitution [Flag(s)]
URLs are Always Relative
The URL you redirect to is always relative to the directory in which your .htaccess file is placed. So if it’s in the root directory, URLs are all in relation to the root directory; if it’s in a sudirectory, URLs are in relation to that particular subdirectory.
A Basic Redirect
If you just want to create a simple 301 redirect from one URL to another, then use the following code:
RewriteRule ^fileone.html$ filetwo.html
This is a very basic rule that means any requests for fileone.html will be sent to filetwo.html.
Require no “www”
This bit of code will make it so visitors to your site don’t need to type in the “www” bit of your website address.
RewriteCond %{HTTP_HOST} !^domain\.com$ [NC] RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]
Block a Specific IP Address
If you want to block someone coming from a specific IP address from accessing your website, you can use the following code:
RewriteCond %{REMOTE_ADDR} ^(A\.B\.C\.D)$ RewriteRule ^/* http://www.domain.com/sorry.html [L]
Replace the A\.B\.C\.D with the IP address you want to block (don’t forget to leave the “\” before each dot, which escapes the character).
0 comments