Welcome to WebmasterWorld Guest from 107.20.59.213

Forum Moderators: Ocean10000 & incrediBILL & phranque

Message Too Old, No Replies

Apache Virtual Host Redirect

Is this right for httpd.conf file

     

vfetty

4:22 am on Jan 16, 2008 (gmt 0)

5+ Year Member



Ok so I have been reading through Apache how to online and banging my head against the wall a little but starting to get it. Basically just trying to turn http://example.com to http://www.example.com/. I have done this successfully with .htaccess but it fails when I go to another directory which employs re-writting the url for search engine friendly urls. So I need a better solution and before I screw with my domain trying to make sure the code below will work for me. Will this change all urls on my site to prefix www? Thanks for taking a look.

<VirtualHost *>
ServerAlias example.com
Redirect permanent / http://www.example.com/
</VirtualHost>

gergoe

11:34 am on Jan 16, 2008 (gmt 0)

10+ Year Member



Yep, this should do what you are looking for. An another way would be to use mod_rewrite indeed (in you normal VirtualHost), but that has some (might be very little) performance penalty, as the server's hostname needs to be checked for each request (even when it is the correct one). So placing it into a separate VirtualHost is the best you can do in my opinion.

lammert

12:21 pm on Jan 16, 2008 (gmt 0)

WebmasterWorld Senior Member lammert is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month



My first VirtualHost section in my httpd.conf is a catch-all box where all requests are going for server names that are not specified in other VirtualHost sections. This is therefore also where all the example.com requests land. I have the following settings in that VirtualHost section:

<VirtualHost my-ip-address:80>

ServerName www-redirect

KeepAlive Off

RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^\./]+\.[^\./]+$
RewriteRule ^/(.*)$ ht tp://www.%{HTTP_HOST}/$1 [R=301,L]

</VirtualHost>

The KeepAlive Off closes the connection directly after the 301 redirect is sent. This makes the apache instance available for new requests. Normally Apache will keep the line open for 15 to 25 seconds, depending on the overall KeepAlive settings in your httpd.conf.

The rewrite part looks voor all requests, where the HTTP_HOST variable contains two parts, separated with a dot. If this condition is met, the rewrite rule places www. at the beginning, and glues the rest of the URL behind the domain name.

This solution works fast because there is no overhead in the VirtualHost section, no cookies sent which may be the case for the main VirtualHost etc, closes the connection to free resources and works for all domains that are pointing to my server at once. No need to program individual rewrite sections for every single site I add to my server.

 

Featured Threads

Hot Threads This Week

Hot Threads This Month