Tutorial

How To Set Up Mod_Rewrite (page 2)

Published on July 11, 2012
How To Set Up Mod_Rewrite (page 2)

Continued from Page 1

Rewrite Conditions

The three examples on the previous page showed how to rewrite URLs to make sites easier to access and remember.

Rewrite Rules can also have conditions to make sure that the rewrites only take place under specific circumstances.

Example 1: How To Prevent Hotlinking

Hotlinking is the process of using an image or object from one server on another one. This action drains bandwidth from the victim's server and denies the creator of the object any additional visitors to their site that they might have gained otherwise.

You can prevent hotlinking by redirecting all the links to an object on your site to some other less pleasant image, or by forbidding the operation altogether.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example\.com/.*$ [NC]
RewriteRule .*\.(gif|jpeg|png)$ http://www.example.com/unpleasantness.jpg [R,NC,L]

Now for an explanation:

  • %{HTTP_REFERER}: this refers to where the traffic is coming from. The percent sign indicates that it is an apache variable.
  • !: the exclamation mark negates the pattern following it. In effect, this points out that whatever follows it does not fall under the conditions required to be affected by the rewrite rule.
  • ^$: As mentioned earlier, the caret stands for the beginning of a string and dollar sign for the end of it. In this case, there is nothing between them and therefore the referrer does not exist. In other words, this line states that direct links are not affected by the rewrite rule.
  • The second condition references the referrer once again.
  • !^http://(www\.)?example\.com/.*$: the exclamation point states that the referrer should not be the our own site
  • Finally we get to the rewrite rule itself which states that any link to a file ending with the extensions gif, jpeg, or png will be rerouted to some unpleasant picture to teach hotlinker a lesson. If we simply wanted to forbid them from accessing any image at all, we can make a small edit to the RewriteRule in the last line. Instead of providing an alternative destination, as this line does, you can instead just send the rewrite to a forbidden page:
    RewriteRule .*\.(gif|jpeg|png)$ - [F]

Example 2: How to add www to a URL

Another useful trick that mod_rewrite can do is add www to a domain. Although it’s easy for a person to see that example.com and www.example.com are the same site, search engines register them as duplicates, hurting their rankings.

To resolve the issue you can choose to either consistently remove the www or always have it added to the URL. This example will show how to be sure that the www is always attached.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301]

Now for an explanation:

  • %{HTTP_HOST}: this refers the website in the requested URL
  • ^example.com$: explains that the requested page needs to be example.com
  • ^(.*)$ :The rewrite rule says that any text after can follow the domain.
  • [R=301]: The flag denotes that the URL as being redirected, and the 301 points out that this is a permanent redirect. A temporary one is designated with the number 302.

Everything will then convert from example.com to www.example.com

Example 3: Blocking a Specific IP Address

This a useful tool to prevent, for example, malicious parties at specific IP addresses from accessing a site.

RewriteCond %{REMOTE_ADDR} ^(12\.34\.56\.789)$
RewriteRule (.*) - [F,L]

Now for an explanation:

  • %{REMOTE_ADDR}: This stands for the IP address from which our site is being accessed and which we want to block.
  • ^(12\.34\.56\.789)$: You can use this section to type in the malicious IP address. Keep in mind that the backslashes are very important. They designate the periods as punctuation, instead of their standard regular expression use as wildcards.
  • (.*): This signifies that any text from the blocked IP will result in the rewrite rule being completed.
  • [F,L]: the flags finish off the rule. [F] forbids access and [L] stops any other rules from applying, making it the last rule.

Resources

The previous sections have been a basic overview of the capabilities of Mod_Rewrite.

The topic is quite expansive and has many nuances that can make it a very useful and flexible tool.

Here are some links for further information about Mod_Rewrite:

By Etel Sverdlov

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
7 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

I am missing one “/” here. When I redirect http://www.olddomain.pt/shop/… I get http://www.newdomain.ptshop/

you can see that between …pt/shop… is missing one “/”

The only way to pass this is put one / in

<VirtualHost *:443> ServerAdmin nunomarques@ioutletstore.pt ServerName http://www.olddomain.pt:443 DocumentRoot /var/www/html/directory Redirect permanent / https://www.newdomain.pt/

<IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTP_HOST} !^www.newdomain.pt RewriteRule .* https://www.newdomain.pt/%{REQUEST_URI} [R=301,L] </IfModule> Regards

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
September 12, 2013

Sweet :]

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
September 10, 2013

@tjcrandall: Try adding trailing slashes to the Redirect directives above. Does that fix it?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
September 9, 2013

@tjcrandall: I recommend getting rid of these .htaccess rules and creating a separate virtualhost for mail.example.com and having it redirect traffic to example.com/mail

It should look like this: <pre><VirtualHost *:80> ServerName mail.example.com

Redirect 301 / http://example.com/mail </VirtualHost></pre>

these tutorials are really saving my days here! Thanks, I will continue to be a digital ocean customer just to show support for these tutorials.

I cant seem to get my permalinks working for wordpress, I get an error not found??

Thanks a lot. I got the permalinks working for my Wordpress Installation.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more