Unix-Apache .htaccess

September 9, 2012

hacking, error pages, redirection, time zone, add-on & sub domains & SEO, hot linking – bandwidth stealing.

.htaccess files (or “distributed configuration files”) allow you to do many different things, … commonly, to have your own custom 404 error pages, to redirect pages, and to enhance security. (for security, see Internet Security

Note 1: Unix used .filename extensions before Microsloth Windoze or even DOS (or CP/M) existed. Unix/Linux uses the convention of a leading period to declare and hide system files, and that is what .htaccess is. It is not “just an extension without a name”. It is a Unix system file for Apache; a configuration file.

Generally not a good idea, potentially confusing, but If you want to call your .htaccess file something else, you can change the name of the file using the AccessFileName directive. For example, if you would rather call the file .config then you can put the following in your server configuration file:

AccessFileName .config

WARNINGS:
Be sure there is a carriage return on your last line.
Be sure there are no leading spaces before the first letter of the first word on the line.
.
Always test, make changes, on your pc or, even better, on a test server first. A simple “typo” or syntax error or error of omission can cause an Apache 500 error, taking down your whole site … causing all visitors to get a “timed out … server not available” error – till you get back on and fix it – and hope you know what you did to cause it.
My worst case senario, so far!, is causing a 500 error on my test pc which not only shot down my test sites but, also, wrecked my ability to see and to access my production sites! – even for several minutes after I fixed it and rebooted my pc! Good that I did it there and not on the server! (make sure your start and end tags always match, like [FilesMatch …] and [/FilesMatch]
Another error: I misspelled a keyword, a simple typo that shot my site down! – and it is hard to see your own typo’s!

Learn from another users mistake:

troubleshooting tips

Fatal Redirection
If you start messing around with 301 redirects [R=301], aka. “Permanently Redirected”, and your rule isn’t working, you could give yourself some serious headaches.

Also, in a shared hosting environment, check your cPanel or Plesk redirection settings. I had never looked at mine and then discovered it was redirecting some things it shouldn’t!

Once the browser has been redirected permanently to the wrong address, if you then go back to fix your error, your browser will still be redirected to the old address (because it’s a browser thing), and you may even go on to fix, and then break the rule all over again without ever knowing it. Changes to 301 redirects can take a long time to show up in your browser.

Solution: restart your browser, or use a different one.
Better Solution: Use [R] instead of [R=301] while you are testing. When you are 100% certain the rule does exactly as it’s expected to, then switch it to [R=301] for your live site.

Note 2: If you must change file names or move pages around, htaccess is the safest, SEO friendly, option for keeping your visitors and maintaining your rankings with Google etc..

An .htaccess file is a simple ASCII file, such as you would create through a text editor, not a word processor.

Many htaccess commands affect the directory they are placed in and all sub-directories. The nearest htaccess file above or in the current directory is the over-riding htaccess file. If the nearest htaccess file is your global htaccess located in your root, then it affects all directories in your site.

When (not) to use .htaccess files

In general, you should not use .htaccess files when you have access to the main server configuration file, otherwise, yes, use them. You have no other choice.

The .htaccess file is requested every time a document is requested – every image etc.. That is a LOT of overhead! You can cache the .htaccess files with aging but will have to remember to manually force it to reload the cache when you make a change, if you do.

Note that it is completely equivalent to put an .htaccess file in a directory /includes/functions/images/ containing a directive, as to put that same directive in your root .htaccess file, or to put it in a Directory section in your main server configuration file: /etc/httpd/conf/httpd.conf

example:
<Directory /www/yoursite/htdocs/includes/functions/images/>
# your directive. #
</Directory>

However, putting this configuration in your server configuration file will result in much less of a performance hit, as the configuration is loaded only once when Apache starts, rather than searched for through multiple folders, every time a file is requested. (!)

After you do make a change to /etc/httpd/conf/httpd.conf you must run “service httpd restart” as root to get Apache to re-read the file and pick up your changes.

for more info on htaccess, visit www.askApache.com/htaccess/htaccess.html


Custom Error Pages

if you want to create a custom error page (give it any appropriate name you wish) and tell Apache about it in htaccess use a line like one of these:
ErrorDocument 404 /error-404.php
or
ErrorDocument 404 /errors/notfound.html

To see the w3school list of all Apache status code definitions from 100 to 505, see
w3.org, Apache status codes

Rather than sending them to an error page, you may wish to simply send a person who tries to find a page or directory that is not found, to the index page

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Custom Index Page

DirectoryIndex filename.html
or
DirectoryIndex filename.html index.cgi index.pl default.htm

If it does not find filename.html, it will then look for index.cgi; if it finds that one, it will load it, if not, it will look for index.pl and the whole process repeats until it finds a file it can use. Basically, the list of files is read from left to right.

Set your Time Zone

example:
SetEnv TZ America/New_York
SetEnv TZ America/Phoenix

Setting you time zone in htaccess means not having to do offsets in php.

See the full list at
http://us2.php.net/manual/en/timezones.php


I have read “FilesMatch should be used instead of Files when dealing with multiple files.” Also, there may be caching going on that interferes with seeing the results. Perhaps, go to a proxy server and double-check from there. (do a Google search on free proxy sites)

Preventing a directory from being listed — Disable Indexing

Some software packages will put an empty index.php file in various folders. However, placing
IndexIgnore *

in your root htaccess file will give a heading with nothing listed under it, or,
Options -Indexes

in your root htaccess file will give a “forbidden!” error.

If, for example, you want to prevent only listing of programs, (ex: .php and .js) use…
IndexIgnore *.php *.js

If you want to allow listing a folder, of images for instance, and all folders under it, put this line in an htaccess file in that folder:
Options +Indexes

protect from spam comments ??

Rarely in .htaccess. Some give lists (as many as 5000!!) of known spammers and hackers to block, but that will drag down your server and only catch a few (none from all the bot-nets). Don’t bother. Check your logs, and when you get a hacker-spammer that has been using one IP for years, block it. Blocking the few that actually have hit you, will not drag down your site like listing several hundred, that don’t even know you, and have never visited you.
Some claim spammers mess up forgetting their HTTP_HOST or HTTP_REFERER or HTTP_USER_AGENT.
like:

RewriteCond %{HTTP_REFERER} !.*yourdomain.com.* [OR] # did not come from your page
RewriteCond %{HTTP_USER_AGENT} ^$ # user agent is empty

A few, but not many, not by my experience today: 2010.

Captcha

The “captcha” methods do work at stopping ALL the automated spam. It seems that spammers don’t even TRY to read the text in the images. In fact, even when you put 2 readable numbers in plain text, they won’t add them! see my wordpress post on stopping spammers.


Redirection

Permanent 301 vs. Temporary 302

Permanent redirects tell the search engines that the old location is to be removed from their index and replaced with the new location.

note: RedirectMatch allows pattern matching and Redirect is only for a single file.

this permanently redirects all requests for /zencart/login.php
RedirectMatch 301 /zencart/login.php /zencart/index.php?main_page=time_out

this permanently redirects all requests for .php files, in the current folder and below, to another site:
RedirectMatch 301 (.*)\.php$ http://www.anothersite.com/

this permanently redirects ALL requests to the current folder and below to the new web site
RedirectMatch 301 (.*) http://www.newwebsite.com/

this redirects everything from the root on down, containing “folder-a” to /folder-b on the same site:
redirectMatch 301 /folder-a /folder-b

note: even though folder-a, folder-b, and .htaccess are all at the same, root, level, the leading slashes are still required.

However, /folder-a/ will not redirect yourwebsite.com/folder-a
Furthermore, /folder-a will also redirect anything like
yourwebsite.com/any/other/path/folder-a to /folder-b
it will even redirect a file like:
yourwebsite.com/any/other/path/folder-a*.php
to /folder-b
which you will not be expecting and might fail to realize even looking at it.

therefore, to redirect a folder anywhere, put the .htaccess redirect in the folder itself
/folder-a/.htaccess
should contain
RedirectMatch 301 (.*) /folder-b

or
RedirectMatch 301 (.*) http://www.newdomain.com

this will redirect yourwebsite.com/folder-a
as well as yourwebsite.com/folder-a/* . . .
to a different folder or even a different website.

this redirects one file/page to another:
RedirectMatch 301 /page-x.html /folder-b/page-y.php

again, the leading slashes (full paths) are required. (?)

also
redirectMatch 301 old-page.php new-page.php
redirectMatch 301 /oldpagename http://domain.com/newpagename
redirectMatch 301 /page2.html http://www.newdomain.com/page2.html
redirectMatch 301 /pic.jpg http://www.newdomain.com/pic.jpg

however, this, below, won’t work because of the “?”, the GET parameter:
RedirectMatch 301 /old-page-xx.php /new/?pg=xxx

you need to use the RewriteRule.

RewriteRule

The basic formula is standard if-then logic: if the request meets a particular CONDITION, then REWRITE the request.

for dynamic URL’s (with GET parameters… aka “query strings”) the RewriteRule is needed:

RewriteEngine on
rewriteRule old-123.php /new/?page=123 [R=301,NC]

the “R=301” or just “R” tells apache that this is a Redirect (perm.)

this, below, won’t work because of the “?”, the GET parameter, in the original page:
#rewriteRule blog/?cat=12 /blog/?page_id=123 [R=301,NC]

to handle both GET parameters, (aka “query string”) this is needed:

RewriteCond %{QUERY_STRING} ^cat=12$
RewriteRule ^blog/?$ /blog/?page_id=123 [L,R=301]

example:
only requests for /grab that have the variable foo set, will be rewritten
RewriteCond %{QUERY_STRING} foo=(.*)
RewriteRule ^grab(.*) /page.php?bar=%1
so:
domain.com/grab?foo=bar
becomes
domain.com/page.php?bar=bar

To redirect the root of your domain to a subfolder:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?YourDomain.com$
RewriteRule ^(/)?$ blog [L]

with or without the www on YourDomain, visitors to the root of your site will be redirected to the folder “blog”

Note: except for strings captured inside a RewriteCond statement, we use % instead of $.


some RewriteCond statement options:

%{REQUEST_FILENAME}
%{SCRIPT_FILENAME}
%{QUERY_STRING}
%{HTTP_REFERER}
%{REQUEST_URI}
%{THE_REQUEST}
%{HTTP_HOST}


ALL OF THEM:

HTTP headers:

HTTP_USER_AGENT
HTTP_REFERER

HTTP_COOKIE
HTTP_FORWARDED
HTTP_HOST
HTTP_PROXY_CONNECTION
HTTP_ACCEPT

connection and request:

REMOTE_ADDR
REMOTE_HOST
REMOTE_USER

REMOTE_IDENT
REQUEST_METHOD
SCRIPT_FILENAME
PATH_INFO
QUERY_STRING
AUTH_TYPE

server internals:

DOCUMENT_ROOT
SERVER_ADMIN

SERVER_NAME
SERVER_ADDR
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE

system stuff:

TIME_YEAR
TIME_MON
TIME_DAY
TIME_HOUR

TIME_MIN
TIME_SEC
TIME_WDAY
TIME

specials:

API_VERSION
THE_REQUEST
REQUEST_URI
REQUEST_FILENAME
IS_SUBREQ

also see http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteCond


Again, the line “RewriteEngine on” must be in each .htaccess file (once) where the RewriteRule is used.

You can use the [QSA] (Query String Append) flag in addition to these query string manipulations, merge them. In the next example, the value of foo becomes the directory in the target URL, and the variable file is created. The original query string is then tagged back onto the end of the whole thing.

RewriteCond %{QUERY_STRING} foo=(.+)
RewriteRule ^grab/(.*) /%1/index.php?file=$1 [QSA]
So
a request for
http://domain.com/grab/foobar.zip?level=5&foo=bar
is translated, server-side, into
http://domain.com/bar/index.php?file=foobar.zip&level=5&foo=bar

or
this might be useful:
RewriteCond %{QUERY_STRING} version=(.+)
RewriteRule ^grab/([^/]+)/(.*) /%1/index.php?section=$1&file=$2 [QSA]

mod_rewrite

The Apache rewrite engine is mainly used to turn dynamic url’s such as www.yoursite.com/product.php?id=123 into static and user friendly url’s such as www.yoursite.com/product/123

example:
www.yoursite.com/cat/product/123/
RewriteRule cat/(.*)/(.*)/$ /script.php?$1=$2
becomes www.yoursite.com/script.php?product=123

Simply, mod_rewrite is used for rewriting a URL at the server level, giving the user output for that final page. So, for example, a user may ask for http://www.somesite.com/widgets/blue/, but will really be given http://www.somesite.com/widgets.php?colour=blue by the server. Of course, the user will see widgets/blue/ not colour=blue

Another Example:

<VirtualHost oldsite.com www.oldsite.com>
Redirect permanent / http://www.newsite.com/
CustomLog logs/redir "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
</VirtualHost>

The “logs/redir” allows you to track just how much the redirect is getting used, and by whom.
Every so often, check it out and you’ll see who still has your old domain name in play.

To Avoid Renaming a Lot of Pages/Files
PHP:
Sometimes you might have a static html website and need to use php code on the html pages. you may tell your server to parse html files as if they were php.
AddHandler application/x-httpd-php .html
or
rename them to .php, to avoid your own confusion later on,
and tell apache that all former .html’s (or .htm’s) are now .php’s:
RewriteRule ^(.*)\.htm$ $1.php [NC]

if someone has been using asp and you want to start using php without changing the names of the pages,
AddHandler application/x-httpd-php .asp

 


 

Parked Domains

If you have several domain names pointed, “parked”, at your site it is a good idea to create permanent 301 redirects for them so for the search engines not to treat them as duplicate content.

A generic solution would be:

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

This also forces the www. prefix onto your domain name, ensuring that it will always be used.

 


 

Add-on Domains

multiple domains in one root

FIRST, you point your new domain name to your servers DNS’s.
SECOND, you add your new domain name in Cpanel: “Addon Domains”

  1. New Domain Name: newdomain.com (put the www. on later, in your .htaccess, if you want it)
  2. Username/directory/subdomain Name: newdomain (the folder = /newdomain/)
  3. Password: somethingNoteasy different and not easy (for FTP…&)

the name of the folder, newdomain, does not have to be the same as in newdomain.com, but for your own sanity, it should be. it can even be newdomain.com if you are going to have a 2nd web site named newdomain.org or newdomain.net, or newdomain.info, or whatever.

When you add http://www.newdomain.com to your Cpanel account, it will do several things….

1) Create newdirectory
2) Setup a pointer to newdirectory.olddomain.com (apache vhost & DNS info)
3) Setup a pointer to http://www.newdomain.com (apache vhost & DNs info)

Anything you upload into newdirectory, for example, index.html can be viewed by going to both http://www.newdomain.com and http://newdirectory.olddomain.com.


Htaccess for addon domains
By Ashley – Apr 14th, 2008

For those of you that make use of add-on domains on your hosting accoumt, its important to setup an .htaccess file to redirect any visitors or bots who find their way to one of the subdomains., to avoid duplicate content issues.

There are three (well six actually!) ways of accessing an add-on domain:

Root domain name (ie. www.addondomain.com)
Subdomain (ie. www.addondomain.the-hosting-domain.com)
Subfolder (ie. www.the-hosting-domain.com/addondomain)

Then of course you have the same three again without the www.

So in order to avoid duplicate sites being spidered and indexed, we can use a few command in the .htaccess file so that all possible names resolve at www.addondomain.com

Here is what you need to put in you htaccess file in the directory that houses your add-on domain ie. www.the-hosting-domain.com/add-on/ :
Code:

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^addondomain\.com [NC]
RewriteRule ^(.*) http://www.addondomain.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www.addondomain.the-hosting-domain\.com
RewriteRule ^(.*)$ http://www.addondomain.com/$1 [R=permanent,L]

RewriteCond %{HTTP_HOST} ^addondomain.the-hosting-domain\.com
RewriteRule ^(.*)$ http://www.addondomain.com/$1 [R=permanent,L] 

actually, the 1st and 3rd can be combined: (either one, anything, without the www.)
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*) http://www.addondomain.com/$1 [R=permanent,L]

And add this to the .htaccess file in the root domain: ie. www.thehostingdomain.com
Code:
Options +FollowSymlinks
RewriteEngine On
Redirect /addondomain http://www.addondomain.com

or … to do the opposite:
RewriteEngine On
RewriteCond %{HTTP_HOST} alias.com$ [NC]
RewriteCond %{REQUEST_URI} !^/alias/.*$
RewriteRule ^(.*)$ /alias/$1 [R=301,L]

“.L” means leave and do no more processing in this .htaccess file


In one case, I put
Redirect /addondomain http://www.addondomain.com
in the .htaccess of the root of the main site
then in the sub-folder, subdomain, htaccess I put

RewriteCond %{HTTP_HOST} ^www.addondomain.the-hosting-domain.com
RewriteRule ^(.*)$ http://www.addondomain.com/$1 [R=permanent,L]

RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*) http://www.addondomain.com/$1 [R=permanent,L]

 


 

Speed – compression

how to compress and cache your site content with Apache and .htaccess file.
Use the mod_deflate module that comes bundled with Apache 2.
Add the following lines to your .htaccess file:

<ifModule mod_deflate.c>
  <filesMatch "\.(css|js|x?html?|php)$">
    SetOutputFilter DEFLATE
  </filesMatch>
</ifModule>

for more good info, see samaxes.com/2009/01/more-on-compressing-and-caching-your-site-with-htaccess/

Add future Expires and Cache-Control headers

A first-time visitor to your page will make several HTTP requests to download all your sites files, but using the Expires and Cache-Control headers you make those files cacheable. This avoids unnecessary HTTP requests on subsequent page views.

To set your Expires headers add these lines to your .htaccess:


ExpiresActive On
ExpiresDefault “access plus 1 seconds”
ExpiresByType text/html “access plus 1 seconds”
ExpiresByType image/gif “access plus 2592000 seconds”
ExpiresByType image/jpeg “access plus 2592000 seconds”
ExpiresByType image/png “access plus 2592000 seconds”
ExpiresByType text/css “access plus 604800 seconds”
ExpiresByType text/javascript “access plus 216000 seconds”
ExpiresByType application/x-javascript “access plus 216000 seconds”

see samaxes.com/2008/04/htaccess-gzip-and-cache-your-site-for-faster-loading-and-bandwidth-saving/

Hardening WordPress security with htaccess:
see blogsecurity.net/wordpress/article-210607

see askapache.com/htaccess/htaccess.html#m0-askapache7

 


 

hot linking — bandwidth stealing

Conditional Statements and mod_rewrite

What happens when you start getting people hotlinking to your images (or other files)? Hot linking is the act of including an image, media file, etc from someone else’s server in one of your own pages as if it were your own. Obviously, as a webmaster, there are plenty of times when you don’t want people doing that. [they are using your bandwidth! and they are probably large files, making it worth their while]

How do you stop it? … a couple of RewriteCond statements in your .htaccess file.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?YourSite\.com/.*$ [NC]
RewriteRule \.(bmp|tif|gif|jpg|jpeg|png)$ - [F]

The – means “don’t rewrite the requested URL”, and the [F] means “Forbidden”. So, the hot linker will get a “403 Forbidden message”, and you don’t end up wasting your bandwidth. Embedded in a page on someone else’s web site, the image just won’t show up.

example for pwsdb.com

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?pwsdb.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?pwsdb.tld/.*$ [NC]
RewriteRule .*\.(jpg|gif|png)$ - [F,NC]

*.tld is the test copy of my site on my pc
it can all be shortened to this:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?pwsdb.*$ [NC]
RewriteRule \.(jpg|gif|png)$ - [F,NC]

note: NC: Not Case-sensitive

examples from 2 of my sites:
the url is listed without and with the “www” separately, here. Both are generated through an option on the cPanel.

this web site:

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?pwsdb.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?pwsdb.com$ [NC]
RewriteRule .*\.(jpg|gif|png)$ - [F,NC]

www.fuel-efficient-vehicles.org ( fevj.org is “parked”)

RewriteCond %{HTTP_REFERER} !^http://(www\.)fevj.org/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)fevj.org$ [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)fuel-efficient-vehicles.org/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)fuel-efficient-vehicles.org$ [NC]
RewriteRule .*\.(jpg|gif|png)$ - [F,NC]

or, instead of stopping it, how about replacing the image they want with one which is an advertisement for your web site!

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?YourSite.com/.*$ [NC]
RewriteCond %{REQUEST_URI} !^/images/my-advertisement.jpg$
RewriteRule \.(bmp|tif|gif|jpg|jpeg|png)$ /images/my-advertisement.jpg [R,L]

if you wish, you can use jpe?g to represent both jpg and jpeg

In either case, the RewriteRule will only be performed if all the preceeding not(!) RewriteConds are fulfilled. In the second RewriteCond, [NC] simply means “No Case”, so it doesn’t matter whether your domain name was written in upper case, lower case or a mixture of the two.
The last line, according to the conditions, denys any requests for gif, jpg, jpeg, or png files from referers other than YourSite.com or, in the 2nd example, will result in our advertisement image being shown instead! … in the 2nd example, notice that an exception is made for my-advertisement.jpg the image you want to use as a substitute – which will, otherwise, be denied also, of course.

OptionalFlags
R : Redirection; optionally, R=301
F : Forbidden. The user will receive a 403 error.
L : Last Rule. No more rules will be processed if this one was successful.

I have also seen an example where exceptions were listed for Google and a few others:

RewriteEngine on
RewriteCond %{HTTP_REFERER} .
RewriteCond %{HTTP_REFERER} !^http://([^.]+\.)?yoursite\. [NC]
RewriteCond %{HTTP_REFERER} !google\. [NC]
RewriteCond %{HTTP_REFERER} !search\?q=cache [NC]
RewriteCond %{HTTP_REFERER} !msn\. [NC]
RewriteCond %{HTTP_REFERER} !yahoo\. [NC]
RewriteCond %{REQUEST_URI} !^/hotlinker\.gif$
RewriteRule \.(gif|jpg|png)$ /hotlinker.gif [NC,L]

SEO and Web Site, Key Word Ranking

Many experts recommend to set up a 301 redirect (permanent redirect) from YourSite.com to www.YourSite.com… (or vice versa)
If your site has been up for a while, do a few Google searches to find out which way Google has been primarily addressing your site.

also, if you are using shared hosting, check your webhost manager, perhaps CPanel or Plesk, as it may have already placed a ‘ServerAlias’ “yoursite.com” or “www.yoursite.com” in the first VirtualHost entry so be sure to check it and remove the ServerAlias there.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^YourSite.com [NC]
RewriteRule (.*) http://www.YourSite.com/$1 [R=301,L]

or

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^yoursite\.com$ [NC]
RewriteRule ^(.*)$ http://yoursite.com/$1 [R=301,L]

this says that each request matching the RewriteCond should be rewritten as follow: put the string that starts with (that’s the ^) any string (that’s the .*) and then finish (that’s the $) in the first variable (called $1), then rewrite as http://yoursite.com/$1 and to redirect using 301-Moved permanently (that’s the R=301) and to stop applying rules from .htaccess (L for Last). This means a request directed to http://www.yoursite.com/index.php?id=1 will be redirected to http://yoursite.com/index.php?id=1

The above example uses a regular expression to match variables: match the part inside (.*) and use it to construct “$1” in the new URL.

This example makes sure folder ‘ggsmith’ is accessed as an independent site, not as a subdomain

RewriteCond %{HTTP_HOST} ^www.ggsmith.fuel-efficient-vehicles.org
RewriteRule ^(.*)$ http://www.ggsmith.net/$1 [R=permanent,L]

RewriteCond %{HTTP_HOST} ^ggsmith.fuel-efficient-vehicles.org
RewriteRule ^(.*) http://www.ggsmith.net/$1 [R=permanent,L]

If SEO and key word ranking is not important to you:
How do you handle more than one domain name pointing to the same Web site? …and still see each name. The lazy way is to set them up as server aliases, which can work pretty well.
It looks like this: (in a file)

<VirtualHost www.birth.net birth.net>
ServerName www.birth.net
ServerAdmin taylor@birth.net
ServerAlias baby.net www.baby.net mothering.net www.mothering.net
ServerAlias apfamilies.org www.apfamilies.org
DocumentRoot /usr/local/etc/httpd/htdocs/birth/
ErrorLog logs/AP/error_log
TransferLog logs/AP/access_log
</VirtualHost>

What these additional ServerAlias lines mean is that anything that comes in for one of the aliased domain names (baby.net, mothering.net, and apfamilies.org) is automatically mapped to the root domain, in this case birth.net. But this means that if there’s a page called, say, “index.shtml”, and someone clicks on the link http://www.mothering.net/index.shtml they’ll be delivered the page that’s at birth.net/index.shtml but the URL they’ll see will be mothering.net, not birth.net.

So that works if you want to seem like you have a number of identical sites under different
domain names.


a site with more advanced details and examples:
http://www.askapache.com/htaccess/htaccess.html


Leave a Reply

We try to post all comments within 1 business day