Saturday, July 10, 2010

installing postfix and dovecot maildir

SkyHi @ Saturday, July 10, 2010
:: what is
- postfix ??
- dovecot ??

:: installing postfix and dovecot on opensuse
[ linux: ~ ]# zypper in postfix dovecot

:: configuration postfix email
[ linux: ~ ]# vi /etc/postfix/main.cf
#
# configuration some like this:

queue_directory = /var/spool/postfix
command_directory = /usr/sbin
daemon_directory = /usr/lib/postfix
data_directory = /var/lib/postfix
mail_owner = postfix
unknown_local_recipient_reject_code = 550


debug_peer_level = 2
debugger_command =
PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
ddd $daemon_directory/$process_name $process_id & sleep 5
sendmail_path = /usr/sbin/sendmail
newaliases_path = /usr/bin/newaliases
mailq_path = /usr/bin/mailq
setgid_group = maildrop
html_directory = /usr/share/doc/packages/postfix/html
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/packages/postfix/samples
readme_directory = /usr/share/doc/packages/postfix/README_FILE
inet_protocols = all
biff = no


myhostname = mail.blackonsole.org
mydomain = blackonsole.org
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mynetworks_style = host
home_mailbox = Maildir/
virtual_mailbox_domains = hash:/etc/postfix/virtual
virtual_mailbox_maps = hash:/etc/postfix/virtual
alias_maps = hash:/etc/aliases


smtp_use_tls = yes
smtp_tls_note_starttls_offer = yes
smtpd_use_tls = yes
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
smtpd_tls_key_file = /etc/ssl/smtpd.pem
smtpd_tls_cert_file = /etc/ssl/smtpd.pem
smtpd_tls_CAfile = /etc/ssl/smtpd.pem
tls_random_source = dev:/dev/urandom
smtpd_recipient_restrictions = permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination,permit

:: make cert
[ linux: postfix ]# cd /etc/ssl/
[ linux: ssl ]# openssl req -new -x509 -nodes -out smtpd.pem -keyout smtpd.pem -days 3650

:: configure dovecot
[ linux: ~ ]# vi /etc/dovecot/dovecot.conf
#
# change on this configuration:

protocols = imap imaps pop3
disable_plaintext_auth = no
ssl = no
auth_debug = yes
auth default {
mechanisms = plain login
passdb pam {
}
passdb shadow {
}
userdb passwd {
}

socket listen {
client {
path = /var/spool/postfix/private/auth
mode = 0660
user = postfix
group = postfix
}
}
}

:: starting postfix and dovecot
[ linux: ~ ]# /etc/init.d/postfix start
[ linux: ~ ]# /etc/init.d/dovecot start

:: links
+ googlelinux
+ wowtutorial
http://www.blackonsole.org/2010/06/install-postfix-dovecot.html

Linux: Subnet (CIDR) Calculator Netmask

SkyHi @ Saturday, July 10, 2010

I'm new to networking and need help with network settings. I'm looking for a tool for calculating available host address ranges with CIDR using Linux command prompt. How do I use subnet calculator under Linux or UNIX?

Linux comes with various IP subnet calculator that will help you with network settings. Once such program is Sipcalc which is an ip subnet calculator. You can install it as follows under Debian or Ubuntu Linux:
$ sudo apt-get update
$ sudo apt-get install sipcalc

Sample outputs:

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
sipcalc
0 upgraded, 1 newly installed, 0 to remove and 51 not upgraded.
Need to get 30.6kB of archives.
After this operation, 123kB of additional disk space will be used.
Get:1 http://archive.ubuntu.com/ubuntu/ lucid/universe sipcalc 1.1.4-2 [30.6kB]
Fetched 30.6kB in 2s (15.1kB/s)
Selecting previously deselected package sipcalc.
(Reading database ... 203411 files and directories currently installed.)
Unpacking sipcalc (from .../sipcalc_1.1.4-2_i386.deb) ...
Processing triggers for man-db ...
Processing triggers for doc-base ...
Processing 1 added doc-base file(s)...
Registering documents with scrollkeeper...
Setting up sipcalc (1.1.4-2) ...

How Do I Calculate Subnets?

$ sipcalc 192.168.1.0/24
Sample outputs:

-[ipv4 : 192.168.1.0/24] - 0

[CIDR]
Host address - 192.168.1.0
Host address (decimal) - 3232235776
Host address (hex) - C0A80100
Network address - 192.168.1.0
Network mask - 255.255.255.0
Network mask (bits) - 24
Network mask (hex) - FFFFFF00
Broadcast address - 192.168.1.255
Cisco wildcard - 0.0.0.255
Addresses in network - 256
Network range - 192.168.1.0 - 192.168.1.255
Usable range - 192.168.1.1 - 192.168.1.254

The above will provide network start & stop range, wildcard, mask and other information. You can calculate 192.168.1.0/24 subnet as follows
$ sipcalc 192.168.1.5/24

Interface Specific Calculation

Instead of taking address information from the shell command line arg sipcalc can obtain relevant information by looking at a specified interface on the system. In this example, get information for eth0 interface:
$ sipcalc eth0
Sample outputs:

-[int-ipv4 : eth0] - 0

[CIDR]
Host address - 192.168.3.254
Host address (decimal) - 3232236542
Host address (hex) - C0A803FE
Network address - 192.168.3.0
Network mask - 255.255.255.0
Network mask (bits) - 24
Network mask (hex) - FFFFFF00
Broadcast address - 192.168.3.255
Cisco wildcard - 0.0.0.255
Addresses in network - 256
Network range - 192.168.3.0 - 192.168.3.255
Usable range - 192.168.3.1 - 192.168.3.254

whatmask Program

Whatmask is a small C program that will help you with network settings. Download and compile it as follows:
$ cd /tmp
$ wget http://downloads.laffeycomputer.com/current_builds/whatmask/whatmask-1.2.tar.gz
$ tar -zxvf whatmask-1.2.tar.gz
$ cd whatmask-1.2/
$ ./configure
$ make
$ sudo make install

You can use it as follows to find out usable ip address with /29:
$ whatmask /29
Sample outputs:

---------------------------------------------
TCP/IP SUBNET MASK EQUIVALENTS
---------------------------------------------
CIDR = .....................: /29
Netmask = ..................: 255.255.255.248
Netmask (hex) = ............: 0xfffffff8
Wildcard Bits = ............: 0.0.0.7
Usable IP Addresses = ......: 6

OR
$ whatmask 202.54.1.2/27
Sample outputs:

------------------------------------------------
TCP/IP NETWORK INFORMATION
------------------------------------------------
IP Entered = ..................: 202.54.1.2
CIDR = ........................: /27
Netmask = .....................: 255.255.255.224
Netmask (hex) = ...............: 0xffffffe0
Wildcard Bits = ...............: 0.0.0.31
------------------------------------------------
Network Address = .............: 202.54.1.0
Broadcast Address = ...........: 202.54.1.31
Usable IP Addresses = .........: 30
First Usable IP Address = .....: 202.54.1.1

Last Usable IP Address = ......: 202.54.1.30

Download software featured in this faq:




REFERENCES
http://www.laffeycomputer.com/whatmask.html
http://www.cyberciti.biz/faq/linux-subnet-calculator-cidr/
http://www.blackonsole.org/2010/07/ip-subnet-calc-with-whatmask.html


Friday, July 9, 2010

SolutionBase: Strengthen network defenses by using a DMZ

SkyHi @ Friday, July 09, 2010
Takeaway: Nations seperate armies through the use of a DMZ, or demilitarized zone. You can seperate your network and users from the threats faced on the Internet by deploying a DMZ as well. Here's what you need to know about how a DMZ works.

The concept of the DMZ, like many other network security
concepts, was borrowed from military terminology. Geopolitically, a
demilitarized zone (DMZ) is an area that runs between two territories that are
hostile to one another or two opposing forces' battle lines. The term was first
widely used to refer to the strip of land that cuts across the Korean peninsula
and separates the North from the South. In computer networking, the DMZ
likewise provides a buffer zone that separates an internal network from the often
hostile territory of the Internet. Sometimes it's called a "screened
subnet" or a "perimeter network," but the purpose remains the
same.





In this article, we'll look at how the DMZ works and
different security architectures for building DMZs. In the second article of
this two-part article, we'll talk about what computers should (and shouldn't)
be placed in the DMZ and how to monitor DMZ activity.





How the DMZ Works



Unlike the geopolitical DMZ, a DMZ network is not a no-man's
land that belongs to nobody. When you create a DMZ for your organization, it
belongs to you and is under your control. However, it is an isolated network
that's separate from your corporate LAN (the "internal" network). The
DMZ uses IP addresses belonging to a different network ID.





If you think of the internal network as the "trusted"
network and the external public network (the Internet) as the "untrusted"
network, you can think of the DMZ as a "semi-trusted" area. It's not
as secured as the LAN, but because it is behind a firewall, neither is it as
non-secure as the Internet. You can also think of the DMZ as a "liaison
network" that can communicate with both the Internet and the LAN while
sitting between the two, as illustrated by Figure A.









Figure A

The DMZ sits between the "hostile" Internet and the internal
corporate network


What does this accomplish? You can place computers that need
to communicate directly with the Internet (public servers) in the DMZ instead
of on your internal network. They will be protected by the outer firewall,
although they are still at risk simply because they have direct contact with
Internet computers. Because the DMZ is only "semi-secure," it's
easier to hack a computer in the DMZ than on the internal network. The good
news is that if a DMZ computer does get hacked, it doesn't compromise the
security of the internal network, because it's on a completely separate,
isolated network.





Why put any computers in this riskier network? Let's take an
example: in order to do its job (make your Web site available to members of the
public), your Web server has to be accessible to the Internet. But having a
server on your network that's accessible from the Internet puts the entire
network at risk. There are three ways to reduce that risk:






  • You could pay
    a hosting company to host your Web sites on their machines and network.
    However, this gives you less control over your Web servers.

  • You could host the public servers on the
    firewall computer. However, best security practices say the firewall computer
    should be dedicated solely to act as a firewall (this reduces the chances of
    the firewall being compromised), and practically speaking, this would impair
    the firewall's performance. Besides, if you have a firewall appliance running a
    proprietary OS, you won't be able to install other services on it.

  • The third solution is to put the public Web
    servers on a separate, isolated network: the DMZ.








Creating a DMZ Infrastructure



The DMZ is created by two basic components: IP addresses and
firewalls. Remember that two important characteristics of the DMZ are:






  1. It has a different network ID from the internal
    network

  2. It is separated from both the Internet and the
    internal network by a firewall






IP Addressing Scheme



A DMZ can use either public or private IP addresses,
depending on its architecture and firewall configuration. If you use public
addresses, you'll usually need to subnet the IP address block that you have
assigned to you by your ISP, so that you have two separate network IDs. One of
the network IDs will be used for the external interface of your firewall and
the other will be used for the DMZ network.





When you subnet your IP address block, you must configure
your router to know how to get to the DMZ subnet.





You can create a DMZ within the same network ID that you use
for your internal network, by using Virtual
LAN (VLAN) tagging.
This is a method of partitioning traffic that shares a
common switch, by creating virtual local area networks as described in IEEE
standard 802.1q. This specification creates a standard way of tagging Ethernet
frames with information about VLAN membership.





If you use private IP addresses for the DMZ, you'll need a
Network Address Translation (NAT) device to translate the private addresses to
a public address at the Internet edge. Some firewalls provide address
translation.





Whether to choose a NAT relationship or a routed
relationship between the Internet and the DMZ depends on the applications you
need to support, as some applications don't work well with NAT.





DMZ Firewalls



When we say that a firewall must separate the DMZ from both
the internal LAN and the Internet, that doesn't necessarily mean you have to
buy two firewalls. If you have a "three legged firewall" (one with at
least three network interfaces), the same firewall can serve both functions. On
the other hand, there are reasons you might want to use two separate firewalls
(a front end and a back end firewall) to create the DMZ.





Figure A above illustrates a DMZ that uses two firewalls,
called a back to back DMZ. An
advantage of this configuration is that you can put a fast packet filtering
firewall/router at the front end (the Internet edge) to increase performance of
your public servers, and place a slower application layer filtering (ALF)
firewall at the back end (next to the corporate LAN) to provide more protection
to the internal network without negatively impacting performance for your
public servers. Each firewall in this configuration has two interfaces. The
front end firewall has an external interface to the Internet and an internal
interface to the DMZ, whereas the backend firewall has an external interface to
the DMZ and an internal interface to the corporate LAN.





When you use a single firewall to create a DMZ, it's called
a trihomed DMZ. That's because the
firewall computer or appliance has interfaces to three separate networks:






  1. The internal interface to the trusted network
    (the internal LAN)

  2. The external interface to the untrusted network
    (the public Internet)

  3. The interface to the semi-trusted network (the
    DMZ)




The trihomed DMZ looks like Figure B.









Figure B

A trihomed DMZ uses a "three legged" firewall to create separate
networks


Even if you use a single trihomed firewall to protect both
the DMZ and the internal network, you should be able to configure separate
rules for evaluating traffic depending on its origin and destination. That is,
there should be separate rules for:






  • Incoming traffic from the Internet to the DMZ

  • Incoming traffic from the DMZ to the internal
    LAN
  • Incoming traffic from the Internet to the
    internal network
  • Outgoing traffic from the internal network to
    the DMZ
  • Outgoing traffic from the internal network to
    the Internet
  • Outgoing traffic from the DMZ to the Internet




The DMZ actually reduces the complexity of filtering
traffic, because you can have one rule for all the computers in the DMZ. If you
were hosting the public servers on the internal network, you would need to
configure different rules for each hosting server, and you would have to "publish"
each server to allow it to be accessed from the Internet.





You'll probably want to block traffic from the Internet to
the internal computers. You should also restrict traffic from the DMZ to the
internal network, as well as traffic from the Internet to the DMZ. Allow only
the traffic that is necessary for your users to access the resources they need.
This means using the "principle of least privilege" in that your
default is to start by denying all traffic and then allowing protocols and
opening ports on a "need to know" basis.





Vendor Support for DMZs



Major hardware and software vendors support the DMZ concept
in their products. Cisco routers have multiple LAN ports, one of which is
designated as a DMZ port, and the IOS operating system uses Port Address
Translation (PAT) to allow traffic to be routed to multiple servers with a
single IP address destination. As the name implies, it uses port numbers (such
as 80 for the Web server and 25 for the mail server) to distinguish between the
multiple servers. This allows you to have multiple public servers without
paying for multiple public IP addresses.





Many firewall appliances, such as the SonicWall, come with
three Ethernet ports: a LAN port (to connect to the internal network), a WAN
port (to connect to the Internet) and a DMZ port (to connect to the network
housing your public servers).





Microsoft's ISA Server 2004's multi-networking feature
allows you to connect the ISA Server firewall to as many networks as you wish,
limited only by the number of network interface cards you can install in the
machine. No network is automatically "trusted" in the new ISA model,
so you configure security according to the needs of the particular network.





Common DMZ Security Architectures



A DMZ is considered by many to be a "wide open" network,
much like the geopolitical DMZ where you risk being shot anytime you set foot
inside it. However, all DMZs are not created equal when it comes to the
security architecture. Even when you place computers in the DMZ, there are
still ways to protect them. The level of security within the DMZ also depends
on the nature of the servers that are placed there. We can divide DMZs into two
security categories:





  1. DMZs designed for unauthenticated or anonymous
    access
  2. DMZs designed for authenticated access




If you have a Web server that you want everybody on the
Internet to be able to access, (such as a Web presence advertising your
company), you'll have to allow anonymous access. You can't easily provide
authentication credentials to every stranger who happens upon your site.
However, if your Internet-facing servers on the DMZ are used by partners,
customers, or employees working off-site, you can require authentication to
access them. This makes it more difficult for a hacker to gain access.





The DMZ Honeynet



There is a special use for the anonymous DMZ that's being
more popular: creating a "honeynet." This is a network that consists
of one or more "honeypot" computers that are designed to lure hackers
--either so they can be caught or tracked, or to divert them from the network's
real resources. Unlike with other DMZs, you actually want this network to be compromised.





Often the computers on the honeynet are virtual machines
that are all installed on a single physical machine, and intrusion detection
systems and other monitoring systems are put in place to gather information
about the hackers' techniques, tactics and identities.





Host Security on the DMZ



Because the DMZ is a less secure network than the internal
network, host security is even more important for the computers that are "out
there." The servers on your DMZ should be hardened as much as possible
(while maintaining their accessibility to those who need to access them). This
means:





  • All unnecessary services should be disabled.
  • Necessary services should be run with the lowest
    privileges possible.
  • Strong passwords or passphrases should be used.
  • Unnecessary user accounts should be deleted or
    disabled and default accounts should be disguised by renaming, changing the
    description, etc.
  • Systems should have the latest security updates
    and patches applied.
  • Security logging should be enabled (and you
    should check the logs frequently!)




The Evolution of the DMZ



The definition of "DMZ" is becoming broader, as
more uses are found for these "semi-trusted" networks. Today's
networks are complex, and security specialists are beginning to realize that
the concept of the network "edge" or "perimeter" is
outdated; an enterprise network has multiple perimeters. Thus, DMZs may be
appropriate at places other than at the edge of the Internet, and large
networks can benefit from having multiple DMZs.


REFERENCES
http://articles.techrepublic.com.com/5100-22_11-5756029.html

Thursday, July 8, 2010

Why do I get the message "(killed lost mailbox lock)" user=... host=...?

SkyHi @ Thursday, July 08, 2010


Solution
The traditional UNIX mailbox format or MMDF format is only allows one session to have the mailbox open read/write at a time. So, the email server assumes that if a second session attempts to open the mailbox, that means that the first session is probably owned by an abandoned client. The common scenario here is a user who leaves his client running at the office, and then tries to read his mail from home. Through an internal mechanism called kiss of death, the second session requests the first session to kill itself. When the first session receives the "kiss of death", it issues the "Killed (lost mailbox lock)" syslog message and terminates. The second session then seizes read/write access, and becomes the new "first" session.



Certain poorly-designed clients routinely open multiple sessions to the same mailbox; the users of those clients tend to get this message a lot.



Another cause of this message is a background "check for new mail" task which does its work by opening a POP session to server every few seconds. They do this because POP doesn't have a way to announce new mail.

REFERENCE
http://www.alphaone-tech.com/tech-support/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=67

Linux command: What is my IP? (Public IP address)

SkyHi @ Thursday, July 08, 2010
Lots of times you need to determine your public IP address, if you are using Linux operating system to power your PC, you may use some good console commands to guess your public IP address.

Using wget

wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$/

Using curl

curl -s checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//'

curl -s http://whatismyip.org/

Using Lynx

lynx -dump checkip.dyndns.org

lynx -dump www.whatismyip.com | grep 'Your IP'

As you can see, there are a lot of ways to check your Public IP address using console commands in Linux.

Of course you can always open a browser and enter any of those URIs and check there.


REFERENCES
http://www.go2linux.org/what-is-my-public-ip-address-with-linux

Wednesday, July 7, 2010

mod_rewrite htaccess Tricks

SkyHi @ Wednesday, July 07, 2010

Welcome to Perishable Press! This article, Stupid htaccess Tricks, covers just about every htaccess “trick” in the book, and is easily the site’s most popular offering. In addition to this htaccess article, you may also want to explore the rapidly expanding htaccess tag archive. Along with all things htaccess, Perishable Press also focuses on (X)HTML, CSS, PHP, JavaScript, security, and just about every other aspect of web design, blogging, and online success. If these topics are of interest to you, I encourage you to subscribe to Perishable Press for a periodic dose of online enlightenment ;)


Table of Contents







General Information [ ^ ]


.htaccess Definition 1 ^


Apache server software provides distributed (i.e., directory-level) configuration via Hypertext Access files. These .htaccess files enable the localized fine-tuning of Apache’s universal system-configuration directives, which are defined in Apache’s main configuration file. The localized .htaccess directives must operate from within a file named .htaccess. The user must have appropriate file permissions to access and/or edit the .htaccess file. Further, .htaccess file permissions should never allow world write access — a secure permissions setting is “644”, which allows universal read access and user-only write access. Finally, .htaccess rules apply to the parent directory and all subdirectories. Thus to apply configuration rules to an entire website, place the .htaccess file in the root directory of the site.


Commenting .htaccess Code ^


Comments are essential to maintaining control over any involved portion of code. Comments in .htaccess code are fashioned on a per-line basis, with each line of comments beginning with a pound sign #. Thus, comments spanning multiple lines in the .htaccess file require multiple pound signs. Further, due to the extremely volatile nature of htaccess voodoo, it is wise to include only alphanumeric characters (and perhaps a few dashes and underscores) in any .htaccess comments.


Important Notes for .htaccess Noobs ^


As a configuration file, .htaccess is very powerful. Even the slightest syntax error (like a missing space) can result in severe server malfunction. Thus it is crucial to make backup copies of everything related to your site (including any original .htaccess files) before working with your Hypertext Access file(s). It is also important to check your entire website thoroughly after making any changes to your .htaccess file. If any errors or other problems are encountered, employ your backups immediately to restore original functionality.


Performance Issues ^


.htaccess directives provide directory-level configuration without requiring access to Apache’s main server cofiguration file (httpd.conf). However, due to performance and security concerns, the main configuration file should always be used for server directives whenever possible. For example, when a server is configured to process .htaccess directives, Apache must search every directory within the domain and load any and all .htaccess files upon every document request. This results in increased page processing time and thus decreases performance. Such a performance hit may be unnoticeable for sites with light traffic, but becomes a more serious issue for more popular websites. Therefore, .htaccess files should only be used when the main server configuration file is inaccessible. See the “Performance Tricks” section of this article for more information.


Regex Character Definitions for htaccess 2 ^


#
the # instructs the server to ignore the line. used for including comments. each line of comments requires it’s own #. when including comments, it is good practice to use only letters, numbers, dashes, and underscores. this practice will help eliminate/avoid potential server parsing errors.
[F]
Forbidden: instructs the server to return a 403 Forbidden to the client.
[L]
Last rule: instructs the server to stop rewriting after the preceding directive is processed.
[N]
Next: instructs Apache to rerun the rewrite rule until all rewriting directives have been achieved.
[G]
Gone: instructs the server to deliver Gone (no longer exists) status message.
[P]
Proxy: instructs server to handle requests by mod_proxy
[C]
Chain: instructs server to chain the current rule with the previous rule.
[R]
Redirect: instructs Apache to issue a redirect, causing the browser to request the rewritten/modified URL.
[NC]
No Case: defines any associated argument as case-insensitive. i.e., "NC" = "No Case".
[PT]
Pass Through: instructs mod_rewrite to pass the rewritten URL back to Apache for further processing.
[OR]
Or: specifies a logical "or" that ties two expressions together such that either one proving true will cause the associated rule to be applied.
[NE]
No Escape: instructs the server to parse output without escaping characters.
[NS]
No Subrequest: instructs the server to skip the directive if internal sub-request.
[QSA]
Append Query String: directs server to add the query string to the end of the expression (URL).
[S=x]
Skip: instructs the server to skip the next "x" number of rules if a match is detected.
[E=variable:value]
Environmental Variable: instructs the server to set the environmental variable "variable" to "value".
[T=MIME-type]
Mime Type: declares the mime type of the target resource.
[]
specifies a character class, in which any character within the brackets will be a match. e.g., [xyz] will match either an x, y, or z.
[]+
character class in which any combination of items within the brackets will be a match. e.g., [xyz]+ will match any number of x’s, y’s, z’s, or any combination of these characters.
[^]
specifies not within a character class. e.g., [^xyz] will match any character that is neither x, y, nor z.
[a-z]
a dash (-) between two characters within a character class ([]) denotes the range of characters between them. e.g., [a-zA-Z] matches all lowercase and uppercase letters from a to z.
a{n}
specifies an exact number, n, of the preceding character. e.g., x{3} matches exactly three x’s.
a{n,}
specifies n or more of the preceding character. e.g., x{3,} matches three or more x’s.
a{n,m}
specifies a range of numbers, between n and m, of the preceding character. e.g., x{3,7} matches three, four, five, six, or seven x’s.
()
used to group characters together, thereby considering them as a single unit. e.g., (perishable)?press will match press, with or without the perishable prefix.
^
denotes the beginning of a regex (regex = regular expression) test string. i.e., begin argument with the proceeding character.
$
denotes the end of a regex (regex = regular expression) test string. i.e., end argument with the previous character.
?
declares as optional the preceding character. e.g., monzas? will match monza or monzas, while mon(za)? will match either mon or monza. i.e., x? matches zero or one of x.
!
declares negation. e.g., “!string” matches everything except “string”.
.
a dot (or period) indicates any single arbitrary character.
-
instructs “not to” rewrite the URL, as in “...domain.com.* - [F]”.
+
matches one or more of the preceding character. e.g., G+ matches one or more G’s, while "+" will match one or more characters of any kind.
*
matches zero or more of the preceding character. e.g., use “.*” as a wildcard.
|
declares a logical “or” operator. for example, (x|y) matches x or y.
\
escapes special characters ( ^ $ ! . * | ). e.g., use “\.” to indicate/escape a literal dot.
\.
indicates a literal dot (escaped).
/*
zero or more slashes.
.*
zero or more arbitrary characters.
^$
defines an empty string.
^.*$
the standard pattern for matching everything.
[^/.]
defines one character that is neither a slash nor a dot.
[^/.]+
defines any number of characters which contains neither slash nor dot.
http://
this is a literal statement — in this case, the literal character string, “http://”.
^domain.*
defines a string that begins with the term “domain”, which then may be proceeded by any number of any characters.
^domain\.com$
defines the exact string “domain.com”.
-d
tests if string is an existing directory
-f
tests if string is an existing file
-s
tests if file in test string has a non-zero value

Redirection Header Codes ^


  • 301 - Moved Permanently
  • 302 - Moved Temporarily
  • 403 - Forbidden
  • 404 - Not Found
  • 410 - Gone

Essentials [ ^ ]


Commenting your htaccess Files ^


It is an excellent idea to consistenly and logically comment your htaccess files. Any line in an htaccess file that begins with the pound sign ( # ) tells the server to ignore it. Multiple lines require multiple pounds and use letters/numbers/dash/underscore only:


# this is a comment

# each line must have its own pound sign

# use only alphanumeric characters along with dashes - and underscores _


Enable Basic Rewriting ^


Certain servers may not have “mod_rewrite” enabled by default. To ensure mod_rewrite (basic rewriting) is enabled throughout your site, add the following line once to your site’s root htaccess file:


# enable basic rewriting

RewriteEngine on


Enable Symbolic Links ^


Enable symbolic links (symlinks) by adding the following directive to the target directory’s htaccess file. Note: for the FollowSymLinks directive to function, AllowOverride Options privileges must be enabled from within the server configuration file (see proceeding paragraph for more information):


# enable symbolic links

Options +FollowSymLinks


Enable AllowOverride ^


For directives that require AllowOverride in order to function, such as FollowSymLinks (see above paragraph), the following directive must be added to the server configuration file. For performance considerations, it is important to only enable AllowOverride in the specific directory or directories in which it is required. In the following code chunk, we are enabling the AllowOverride privs only in the specified directory (/www/replace/this/with/actual/directory). Refer to this section for more information about AllowOverride and performance enhancement:


# enable allowoverride privileges

<Directory /www/replace/this/with/actual/directory>

 AllowOverride Options

</Directory>


Rename the htaccess File ^


Not every system enjoys the extension-only format of htaccess files. Fortunately, you can rename them to whatever you wish, granted the name is valid on your system. Note: This directive must be placed in the server-wide configuration file or it will not work:


# rename htaccess files

AccessFileName ht.access


Note: If you rename your htaccess files, remember to update any associated configuration settings. For example, if you are protecting your htaccess file via FilesMatch, remember to inform it of the renamed files:


# protect renamed htaccess files

<FilesMatch "^ht\.">

 Order deny,allow

 Deny from all

</FilesMatch>


Retain Rules Defined in httpd.conf ^


Save yourself time and effort by defining replicate rules for multiple virtual hosts once and only once via your httpd.conf file. Then, simply instruct your target htaccess file(s) to inherit the httpd.conf rules by including this directive:


RewriteOptions Inherit


Performance [ ^ ]


Improving Performance via AllowOverride ^


Limit the extent to which htaccess files decrease performance by enabling AllowOverride only in required directories. For example, if AllowOverride is enabled throughout the entire site, the server must dig through every directory, searching for htaccess files that may not even exist. To prevent this, we disable the AllowOverride in the site’s root htaccess file and then enable AllowOverride only in required directories via the server config file (refer to this section for more information). Note: if you do not have access to your site’s server config file and also need AllowOverride privileges, do not use this directive:


# increase performance by disabling allowoverride

AllowOverride None


Improving Performance by Passing the Character Set ^


Prevent certain 500 error displays by passing the default character set parameter before you get there. Note: replace the “utf-8” below with the charset that your site is using:


# pass the default character set

AddDefaultCharset utf-8


Improving Performance by Preserving Bandwidth ^


To increase performance on PHP enabled servers, add the following directive:


# preserve bandwidth for PHP enabled servers

<ifmodule mod_php4.c>

 php_value zlib.output_compression 16386

</ifmodule>


Disable the Server Signature ^


Here we are disabling the digital signature that would otherwise identify the server:


# disable the server signature

ServerSignature Off


Set the Server Timezone ^


Here we are instructing the server to synchronize chronologically according to the time zone of some specified state:


# set the server timezone

SetEnv TZ America/Washington


Set the Email Address for the Server Administrator ^


Here we are specifying the default email address for the server administrator:


# set the server administrator email

SetEnv SERVER_ADMIN default@domain.com


Improve Site Transfer Speed by Enabling File Caching ^


The htaccess genius over at askapache.com explains how to dramatically improve your site’s transfer speed by enabling file caching 3. Using time in seconds* to indicate the duration for which cached content should endure, we may generalize the htaccess rules as such (edit file types and time value to suit your needs):


# cache images and flash content for one month

<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf)$">

Header set Cache-Control "max-age=2592000"

</FilesMatch>


# cache text, css, and javascript files for one week

<FilesMatch ".(js|css|pdf|txt)$">

Header set Cache-Control "max-age=604800"

</FilesMatch>


# cache html and htm files for one day

<FilesMatch ".(html|htm)$">

Header set Cache-Control "max-age=43200"

</FilesMatch>


# implement minimal caching during site development

<FilesMatch "\.(flv|gif|jpg|jpeg|png|ico|js|css|pdf|swf|html|htm|txt)$">

Header set Cache-Control "max-age=5"

</FilesMatch>


# explicitly disable caching for scripts and other dynamic files

<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">

Header unset Cache-Control

</FilesMatch>


# alternate method for file caching

ExpiresActive On

ExpiresDefault A604800 # 1 week

ExpiresByType image/x-icon A2419200 # 1 month

ExpiresByType application/x-javascript A2419200 # 1 month

ExpiresByType text/css A2419200 # 1 month

ExpiresByType text/html A300 # 5 minutes

# disable caching for scripts and other dynamic files

<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">

ExpiresActive Off

</FilesMatch>


  • * Convert common time intervals into seconds:
  • 300 = 5 minutes
  • 2700 = 45 minutes
  • 3600 = 1 hour
  • 54000 = 15 hours
  • 86400 = 1 day
  • 518400 = 6 days
  • 604800 = 1 week
  • 1814400 = 3 weeks
  • 2419200 = 1 month
  • 26611200 = 11 months
  • 29030400 = 1 year = never expires

Set the default language and character set ^


Here is an easy way to set the default language for pages served by your server (edit the language to suit your needs):


# set the default language

DefaultLanguage en-US


Likewise, here we are setting the default character set (edit to taste):


# set the default character set

AddDefaultCharset UTF-8


Declare specific/additional MIME types ^


# add various mime types

AddType application/x-shockwave-flash .swf

AddType video/x-flv .flv

AddType image/x-icon .ico


Send character set and other headers without meta tags ^


# send the language tag and default character set

# AddType 'text/html; charset=UTF-8' html

AddDefaultCharset UTF-8

DefaultLanguage en-US


Limit server request methods to GET and PUT ^


# limit server request methods to GET and PUT

Options -ExecCGI -Indexes -All

RewriteEngine on

RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD) RewriteRule .* - [F]


Selectively process files according to server request method ^


# process files according to server request method

Script PUT /cgi-bin/upload.cgi

Script GET /cgi-bin/download.cgi


Execute various file types through a cgi script ^


For those special occasions where certain file types need to be processed with some specific cgi script, let em know who sent ya:


# execute all png files via png-script.cgi

Action image/png /cgi-bin/png-script.cgi


Security [ ^ ]


Prevent Access to .htaccess ^


Add the following code block to your htaccess file to add an extra layer of security. Any attempts to access the htaccess file will result in a 403 error message. Of course, your first layer of defense to protect htaccess files involves setting htaccess file permissions via CHMOD to 644:


# secure htaccess file

<Files .htaccess>

 order allow,deny

 deny from all

</Files>


Prevent Acess to a Specific File ^


To restrict access to a specific file, add the following code block and edit the file name, “secretfile.jpg”, with the name of the file that you wish to protect:


# prevent viewing of a specific file

<files secretfile.jpg>

 order allow,deny

 deny from all

</files>


Prevent acess to multiple file types ^


To restrict access to a variety of file types, add the following code block and edit the file types within parentheses to match the extensions of any files that you wish to protect:


<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">

 Order Allow,Deny

 Deny from all

</FilesMatch>


Prevent Unauthorized Directory Browsing ^


Prevent unauthorized directory browsing by instructing the server to serve a “xxx Forbidden - Authorization Required” message for any request to view a directory. For example, if your site is missing it’s default index page, everything within the root of your site will be accessible to all visitors. To prevent this, include the following htaccess rule:


# disable directory browsing

Options All -Indexes


Conversely, to enable directory browsing, use the following directive:


# enable directory browsing

Options All +Indexes


Likewise, this rule will prevent the server from listing directory contents:


# prevent folder listing

IndexIgnore *


And, finally, the IndexIgnore directive may be used to prevent the display of select file types:


# prevent display of select file types

IndexIgnore *.wmv *.mp4 *.avi *.etc


Change Default Index Page ^


This rule tells the server to search for and serve “business.html” as the default directory index. This rule must exist in the htaccess files of the root directory for which you wish to replace the default index file (e.g., “index.html”):


# serve alternate default index page

DirectoryIndex business.html


This rule is similar, only in this case, the server will scan the root directory for the listed files and serve the first match it encounters. The list is read from left to right:


# serve first available alternate default index page from series

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


Disguise Script Extensions ^


To enhance security, disguise scripting languages by replacing actual script extensions with dummy extensions of your choosing. For example, to change the “.foo” extension to “.php”, add the following line to your htaccess file and rename all affected files accordingly:


# serve foo files as php files

AddType application/x-httpd-php .foo


# serve foo files as cgi files

AddType application/x-httpd-cgi .foo


Limit Access to the Local Area Network (LAN) ^


# limit access to local area network

<Limit GET POST PUT>

 order deny,allow

 deny from all

 allow from 192.168.0.0/33

</Limit>


Secure Directories by IP Address and/or Domain ^


In the following example, all IP addresses are allowed access except for 12.345.67.890 and domain.com:


# allow all except those indicated here

<Limit GET POST PUT>

 order allow,deny

 allow from all

 deny from 12.345.67.890

 deny from .*domain\.com.*

</Limit>


In the following example, all IP addresses are denied access except for 12.345.67.890 and domain.com:


# deny all except those indicated here

<Limit GET POST PUT>

 order deny,allow

 deny from all

 allow from 12.345.67.890

 allow from .*domain\.com.*

</Limit>


This is how to block unwanted visitors based on the referring domain. You can also save bandwidth by blocking specific file types — such as .jpg, .zip, .mp3, .mpg — from specific referring domains. Simply replace “scumbag” and “wormhole” with the offending domains of your choice:


# block visitors referred from indicated domains

<IfModule mod_rewrite.c>

 RewriteEngine on

 RewriteCond %{HTTP_REFERER} scumbag\.com [NC,OR]

 RewriteCond %{HTTP_REFERER} wormhole\.com [NC,OR]

 RewriteRule .* - [F]

</ifModule>


Prevent or allow domain access for a specified range of IP addresses ^


There are several effective ways to block a range of IP addresses via htaccess. This first method blocks an IP range specified by their CIDR (Classless Inter-Domain Routing) number. This method is useful for blocking mega-spammers such as RIPE, Optinet, and others. If, for example, you find yourself adding line after line of Apache deny directives for addresses beginning with the same first few numbers, choose one of them and try a whois lookup. Listed within the whois results will be the CIDR value representing every IP address associated with that particular network. Thus, blocking via CIDR is an effective way to eloquently prevent all IP instances of the offender from accessing your site. Here is a generalized example for blocking by CIDR (edit values to suit your needs):


# block IP range by CIDR number

<Limit GET POST PUT>

 order allow,deny

 allow from all

 deny from 10.1.0.0/16

 deny from 80.0.0/8

</Limit>


Likewise, to allow an IP range by CIDR number:


# allow IP range by CIDR number

<Limit GET POST PUT>

 order deny,allow

 deny from all

 allow from 10.1.0.0/16

 allow from 80.0.0/8

</Limit>


Another effective way to block an entire range of IP addresses involves truncating digits until the desired range is represented. As an IP address is read from left to right, its value represents an increasingly specific address. For example, a fictitious IP address of 99.88.77.66 would designate some uniquely specific IP address. Now, if we remove the last two digits (66) from the address, it would represent any address beginning with the remaining digits. That is, 99.88.77 represents 99.88.77.1, 99.88.77.2, … 99.88.77.99, …etc. Likewise, if we then remove another pair of digits from the address, its range suddenly widens to represent every IP address 99.88.x.y, where x and y represent any valid set of IP address values (i.e., you would block 256*256 = 65,536 unique IP addresses). Following this logic, it is possible to block an entire range of IP addresses to varying degrees of specificity. Here are few generalized lines exemplifying proper htaccess syntax (edit values to suit your needs):


# block IP range by address truncation

<Limit GET POST PUT>

 order allow,deny

 allow from all

 deny from 99.88.77.66

 deny from 99.88.77.*

 deny from 99.88.*.*

 deny from 99.*.*.*

</Limit>


Likewise, to allow an IP range by address truncation:


# allow IP range by address truncation

<Limit GET POST PUT>

 order deny,allow

 deny from all

 allow from 99.88.77.66

 allow from 99.88.77.*

 allow from 99.88.*.*

 allow from 99.*.*.*

</Limit>


Block or allow multiple IP addresses on one line ^


Save a little space by blocking multiple IP addresses or ranges on one line. Here are few examples (edit values to suit your needs):


# block two unique IP addresses

deny from 99.88.77.66 11.22.33.44

# block three ranges of IP addresses

deny from 99.88 99.88.77 11.22.33


Likewise, to allow multiple IP addresses or ranges on one line:


# allow two unique IP addresses

allow from 99.88.77.66 11.22.33.44

# allow three ranges of IP addresses

allow from 99.88 99.88.77 11.22.33


Miscellaneous rules for blocking and allowing IP addresses ^


Here are few miscellaneous rules for blocking various types of IP addresses. These rules may be adapted to allow the specified IP values by simply changing the deny directive to allow. Check ’em out (edit values to suit your needs):


# block a partial domain via network/netmask values

deny from 99.1.0.0/255.255.0.0


# block a single domain

deny from 99.88.77.66


# block domain.com but allow sub.domain.com

order deny,allow

deny from domain.com

allow from sub.domain.com


Stop Hotlinking, Serve Alternate Content ^


To serve ‘em some unexpected alternate content when hotlinking is detected, employ the following code, which will protect all files of the types included in the last line (add more types as needed). Remember to replace the dummy path names with real ones. Also, the name of the nasty image being served in this case is “eatme.jpe”, as indicated in the line containing the RewriteRule. Please advise that this method will also block services such as FeedBurner from accessing your images.


# stop hotlinking and serve alternate content

<IfModule mod_rewrite.c>

 RewriteEngine on

 RewriteCond %{HTTP_REFERER} !^$

 RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.com/.*$ [NC]

 RewriteRule .*\.(gif|jpg)$ http://www.domain.com/eatme.jpe [R,NC,L]

</ifModule>


Note: To deliver a standard (or custom, if configured) error page instead of some nasty image of the Fonz, replace the line containing the RewriteRule in the above htaccess directive with the following line:


# serve a standard 403 forbidden error page

RewriteRule .*\.(gif|jpg)$ - [F,L]


Note: To grant linking permission to a site other than yours, insert this code block after the line containing the “domain.com” string. Remember to replace “goodsite.com” with the actual site domain:


# allow linking from the following site

RewriteCond %{HTTP_REFERER} !^http://(www\.)?goodsite\.com/.*$ [NC]


Block Evil Robots, Site Rippers, and Offline Browsers ^


Eliminate some of the unwanted scum from your userspace by injecting this handy block of code. After such, any listed agents will be denied access and receive an error message instead. Please advise that there are much more comprehensive lists available this example has been truncated for business purposes. Note: DO NOT include the “[OR]” on the very last RewriteCond or your server will crash, delivering “500 Errors” to all page requests.


# deny access to evil robots site rippers offline browsers and other nasty scum

RewriteBase /

RewriteCond %{HTTP_USER_AGENT} ^Anarchie [OR]

RewriteCond %{HTTP_USER_AGENT} ^ASPSeek [OR]

RewriteCond %{HTTP_USER_AGENT} ^attach [OR]

RewriteCond %{HTTP_USER_AGENT} ^autoemailspider [OR]

RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]

RewriteCond %{HTTP_USER_AGENT} ^Xenu [OR]

RewriteCond %{HTTP_USER_AGENT} ^Zeus.*Webster [OR]

RewriteCond %{HTTP_USER_AGENT} ^Zeus

RewriteRule ^.* - [F,L]


Or, instead of delivering a friendly error message (i.e., the last line), send these bad boys to the hellish website of your choice by replacing the RewriteRule in the last line with one of the following two examples:


# send em to a hellish website of your choice

RewriteRule ^.*$ http://www.hellish-website.com [R,L]


Or, to send em to a virtual blackhole of fake email addresses:


# send em to a virtual blackhole of fake email addresses

RewriteRule ^.*$ http://english-61925045732.spampoison.com [R,L]


You may also include specific referrers to your blacklist by using HTTP_REFERER. Here, we use the infamously scummy domain, “iaea.org” as our blocked example, and we use “yourdomain” as your domain (the domain to which you are blocking iaea.org):


RewriteCond %{HTTP_REFERER} ^http://www.iaea.org$

RewriteRule !^http://[^/.]\.yourdomain\.com.* - [F,L]


More Stupid Blocking Tricks ^


Note: Although these redirect techniques are aimed at blocking and redirecting nasty scumsites, the directives may also be employed for friendly redirection purposes:


# redirect any request for anything from spamsite to differentspamsite

RewriteCond %{HTTP_REFERER} ^http://.*spamsite.*$ [NC]

RewriteRule .* http://www.differentspamsite.com [R]


# redirect all requests from spamsite to an image of something at differentspamsite

RewriteCond %{HTTP_REFERER} ^http://.*spamsite.*$ [NC]

RewriteRule .* http://www.differentspamsite/something.jpg [R]


# redirect traffic from a certain address or range of addresses to another site

RewriteCond %{REMOTE_ADDR} 192.168.10.*

RewriteRule .* http://www.differentspamsite.com/index.html [R]


Even More Scum-Blocking Tricks ^


Here is a step-by-step series of code blocks that should equip you with enough knowledge to block any/all necessary entities. Read through the set of code blocks, observe the patterns, and then copy, combine and customize to suit your specific scum-blocking needs:


# set variables for user agents and referers and ip addresses

SetEnvIfNoCase User-Agent ".*(user-agent-you-want-to-block|php/perl).*" BlockedAgent

SetEnvIfNoCase Referer ".*(block-this-referrer|and-this-referrer|and-this-referrer).*" BlockedReferer

SetEnvIfNoCase REMOTE_ADDR ".*(666.666.66.0|22.22.22.222|999.999.99.999).*" BlockedAddress


# set variable for any class B network coming from a given netblock

SetEnvIfNoCase REMOTE_ADDR "66.154.*" BlockedAddress


# set variable for two class B networks 198.25.0.0 and 198.26.0.0

SetEnvIfNoCase REMOTE_ADDR "198.2(5|6)\..*" BlockedAddress


# deny any matches from above and send a 403 denied

<Limit GET POST PUT>

 order deny,allow

 deny from env=BlockedAgent

 deny from env=BlockedReferer

 deny from env=BlockedAddress

 allow from all

</Limit>


Password-Protect Directories ^


Here is an excellent online tool for generating the necessary elements for a password-protected directory:


# password protect directories

htaccess Password Generator


Password-protect Files, Directories, and More.. ^


Secure site contents by requiring user authentication for specified files and/or directories. The first example shows how to password-protect any single file type that is present beneath the directory which houses the htaccess rule. The second rule employs the FilesMatch directive to protect any/all files which match any of the specified character strings. The third rule demonstrates how to protect an entire directory. The fourth set of rules provides password-protection for all IP’s except those specified. Remember to edit these rules according to your specific needs.


# password-protect single file

<Files secure.php>

AuthType Basic

AuthName "Prompt"

AuthUserFile /home/path/.htpasswd

Require valid-user

</Files>


# password-protect multiple files

<FilesMatch "^(execute|index|secure|insanity|biscuit)*$">

AuthType basic

AuthName "Development"

AuthUserFile /home/path/.htpasswd

Require valid-user

</FilesMatch>


# password-protect the directory in which this htaccess rule resides

AuthType basic

AuthName "This directory is protected"

AuthUserFile /home/path/.htpasswd

AuthGroupFile /dev/null

Require valid-user


# password-protect directory for every IP except the one specified

# place in htaccess file of a directory to protect that entire directory

AuthType Basic

AuthName "Personal"

AuthUserFile /home/path/.htpasswd

Require valid-user

Allow from 99.88.77.66

Satisfy Any


Require SSL (Secure Sockets Layer) ^


Here is an excellent method for requiring SSL (via askapache.com 3):


# require SSL

SSLOptions +StrictRequire

SSLRequireSSL

SSLRequire %{HTTP_HOST} eq "domain.tld"

ErrorDocument 403 https://domain.tld


# require SSL without mod_ssl

RewriteCond %{HTTPS} !=on [NC]

RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]


Automatically CHMOD Various File Types ^


This method is great for ensuring the CHMOD settings for various file types. Employ the following rules in the root htaccess file to affect all specified file types, or place in a specific directory to affect only those files (edit file types according to your needs):


# ensure CHMOD settings for specified file types

# remember to never set CHMOD 777 unless you know what you are doing

# files requiring write access should use CHMOD 766 rather than 777

# keep specific file types private by setting their CHMOD to 400

chmod .htpasswd files 640

chmod .htaccess files 644

chmod php files 600


Disguise all file extensions ^


This method will disguise all file types (i.e., any file extension) and present them as .php files (or whichever extension you choose):


# diguise all file extensions as php

ForceType application/x-httpd-php


Protect against denial-of-service (DOS) attacks by limiting file upload size ^


One method to help protect your server against DOS attacks involves limiting the maximum allowable size for file uploads. Here, we are limiting file upload size to 10240000 bytes, which is equivalent to around 10 megabytes. For this rule, file sizes are expressed in bytes. Check here for help with various file size conversions. Note: this code is only useful if you actually allow users to upload files to your site.


# protect against DOS attacks by limiting file upload size

LimitRequestBody 10240000


Secure directories by disabling execution of scripts ^


Prevent malicious brainiacs from actively scripting secure directories by adding the following rules to the representative htaccess file (edit file types to suit your needs):


# secure directory by disabling script execution

AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi

Options -ExecCGI


Usability Tricks [ ^ ]


Minimize CSS Image Flicker in IE6 ^


Add the following htaccess rules to minimize or even eliminate CSS background-image “flickering” in MSIE6:


# minimize image flicker in IE6

ExpiresActive On

ExpiresByType image/gif A2592000

ExpiresByType image/jpg A2592000

ExpiresByType image/png A2592000


Deploy Custom Error Pages ^


Replicate the following patterns to serve your own set of custom error pages. Simply replace the “/errors/###.html” with the correct path and file name. Also change the “###” preceding the path to summon pages for other errors. Note: your custom error pages must be larger than 512 bytes in size or they will be completely ignored by Internet Explorer:


# serve custom error pages

ErrorDocument 400 /errors/400.html

ErrorDocument 401 /errors/401.html

ErrorDocument 403 /errors/403.html

ErrorDocument 404 /errors/404.html

ErrorDocument 500 /errors/500.html


Provide a Universal Error Document ^


# provide a universal error document

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^.*$ /dir/error.php [L]


Employ Basic URL Spelling Check ^


This bit of voodoo will auto-correct simple spelling errors in the URL:


# automatically corect simple speling erors

<IfModule mod_speling.c>

 CheckSpelling On

</IfModule>


Instruct browser to download multimedia files rather than display them ^


Here is a useful method for delivering multimedia file downloads to your users. Typically, browsers will attempt to play or stream such files when direct links are clicked. With this method, provide a link to a multimedia file and a dialogue box will provide users the choice of saving the file or opening it. Here are a few htaccess rules demonstrating the technique (edit file types according to your specific needs):


# instruct browser to download multimedia files

AddType application/octet-stream .avi

AddType application/octet-stream .mpg

AddType application/octet-stream .wmv

AddType application/octet-stream .mp3


Instruct server to display source code for dynamic file types ^


There are many situations where site owners may wish to display the contents of a dynamic file rather than executing it as a script. To exercise this useful technique, create a directory in which to place dynamic files that should be displayed rather than executed, and add the following line of code to the htaccess file belonging to that directory. This method is known to work for .pl, .py, and .cgi file-types. Here it is:


RemoveHandler cgi-script .pl .py .cgi


Redirect visitors to a temporary site during site development ^


During web development, maintenance, or repair, send your visitors to an alternate site while retaining full access for yourself. This is a very useful technique for preventing visitor confusion or dismay during those awkward, web-development moments. Here are the generalized htaccess rules to do it (edit values to suit your needs):


# redirect all visitors to alternate site but retain full access for you

ErrorDocument 403 http://www.alternate-site.com

Order deny,allow

Deny from all

Allow from 99.88.77.66


Provide a password prompt for visitors during site development ^


Here is another possible solution for "hiding" your site during those private, site-under-construction moments. Here we are instructing Apache to provide visitors with a password prompt while providing open access to any specifically indicated IP addresses or URL’s. Edit the following code according to your IP address and other development requirements (thanks to Caleb at askapache.com for sharing this trick 3):


# password prompt for visitors

AuthType basic

AuthName "This site is currently under construction"

AuthUserFile /home/path/.htpasswd

AuthGroupFile /dev/null

Require valid-user

# allow webmaster and any others open access

Order Deny,Allow

Deny from all

Allow from 111.222.33.4

Allow from favorite.validation/services/

Allow from googlebot.com

Satisfy Any


Prevent file or directory access according to specified time periods ^


Prevent viewing of all pictures of Fonzi during the midnight hour — or any files during any time period — by using this handy htaccess ruleset:


# prevent access during the midnight hour

RewriteCond %{TIME_HOUR} ^12$

RewriteRule ^.*$ - [F,L]


# prevent access throughout the afternoon

RewriteCond %{TIME_HOUR} ^(12|13|14|15)$

RewriteRule ^.*$ - [F,L]


Redirect Tricks [ ^ ]


Important Note About Redirecting via mod_rewrite ^


For all redirects using the mod_rewrite directive, it is necessary to have the RewriteEngine enabled. It is common practice to enable the mod_rewrite directive in either the server configuration file or at the top of the site’s root htaccess file. If the mod_rewrite directive is not included in either of these two places, it should be included as the first line in any code block that utilizes a rewrite function (i.e., mod_rewrite), but only needs to be included once for each htaccess file. The proper mod_rewrite directive is included here for your convenience, but may or may not also be included within some of the code blocks provided in this article:


# initialize and enable rewrite engine

RewriteEngine on


Redirect from http://www.domain.com to http://domain.com ^


This method uses a “301 redirect” to establish a permanent redirect from the “www-version” of a domain to its respectively corresponding “non-www version”. Be sure to test immediately after preparing 301 redirects and remove it immediately if any errors occur. Use a “server header checker” to confirm a positive 301 response. Further, always include a trailing slash “/” when linking directories. Finally, be consistent with the “www” in all links (either use it always or never).


# permanently redirect from www domain to non-www domain

RewriteEngine on

Options +FollowSymLinks

RewriteCond %{HTTP_HOST} ^www\.domain\.tld$ [NC]

RewriteRule ^(.*)$ http://domain.tld/$1 [R=301,L]


Redirect from http://old-domain.com to http://new-domain.com ^


For a basic domain change from “old-domain.com” to “new-domain.com” (and folder/file names have not been changed), use the Rewrite rule to remap the old domain to the new domain. When checking the redirect live, the old domain may appear in the browser’s address bar. Simply check an image path (right-click an image and select “properties”) to verify proper redirection. Remember to check your site thoroughly after implementing this redirect.


# redirect from old domain to new domain

RewriteEngine On

RewriteRule ^(.*)$ http://www.new-domain.com/$1 [R=301,L]


Redirect String Variations to a Specific Address ^


For example, if we wanted to redirect any requests containing the character string, “perish”, to our main page at http://perishablepress.com/, we would replace “some-string” with “perish” in the following code block:


# redirect any variations of a specific character string to a specific address

RewriteRule ^some-string http://www.domain.com/index.php/blog/target [R]


Here are two other methods for accomplishing string-related mapping tasks:


# map URL variations to the same directory on the same server

AliasMatch ^/director(y|ies) /www/docs/target


# map URL variations to the same directory on a different server

RedirectMatch ^/[dD]irector(y|ies) http://domain.com


Other Fantastic Redirect Tricks ^


Redirect an entire site via 301:


# redirect an entire site via 301

redirect 301 / http://www.domain.com/


Redirect a specific file via 301:


# redirect a specific file via 301

redirect 301 /current/currentfile.html http://www.newdomain.com/new/newfile.html


Redirect an entire site via permanent redirect:


# redirect an entire site via permanent redirect

Redirect permanent / http://www.domain.com/


Redirect a page or directory via permanent redirect:


# redirect a page or directory

Redirect permanent old_file.html http://www.new-domain.com/new_file.html

Redirect permanent /old_directory/ http://www.new-domain.com/new_directory/


Redirect a file using RedirectMatch:


# redirect a file using RedirectMatch

RedirectMatch 301 ^.*$ http://www.domain.com/index.html


Note: When redirecting specific files, use Apache‘s Redirect rule for files within the same domain. Use Apache‘s RewriteRule for any domains, especially if they are different. The RewriteRule is more powerful than the Redirect rule, and thus should serve you more effectively.


Thus, use the following for a stronger, harder page redirection (first line redirects a file, second line a directory, and third a domain):


# redirect files directories and domains via RewriteRule

RewriteRule http://old-domain.com/old-file.html http://new-domain.com/new-file.html

RewriteRule http://old-domain.com/old-dir/ http://new-domain.com/new-dir/

RewriteRule http://old-domain.com/ http://new-domain.com/


Send visitors to a subdomain ^


This rule will ensure that all visitors are viewing pages via the subdomain of your choice. Edit the "subdomain", "domain", and "tld" to match your subdomain, domain, and top-level domain respectively:


# send visitors to a subdomain

RewriteCond %{HTTP_HOST} !^$

RewriteCond %{HTTP_HOST} !^subdomain\.domain\.com$ [NC]

RewriteRule ^/(.*)$ http://subdomain.domain.tld/$1 [L,R=301]


More fun with RewriteCond and RewriteRule ^


# rewrite only if the file is not found

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.+)special\.html?$ cgi-bin/special/special-html/$1


# rewrite only if an image is not found

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule images/special/(.*).gif cgi-bin/special/mkgif?$1


# seo-friendly rewrite rules for various directories

RewriteRule ^(.*)/aud/(.*)$ $1/audio-files/$2 [L,R=301]

RewriteRule ^(.*)/img/(.*)$ $1/image-files/$2 [L,R=301]

RewriteRule ^(.*)/fla/(.*)$ $1/flash-files/$2 [L,R=301]

RewriteRule ^(.*)/vid/(.*)$ $1/video-files/$2 [L,R=301]


# broswer sniffing via htaccess environmental variables

RewriteCond %{HTTP_USER_AGENT} ^Mozilla.*

RewriteRule ^/$ /index-for-mozilla.html [L]

RewriteCond %{HTTP_USER_AGENT} ^Lynx.*

RewriteRule ^/$ /index-for-lynx.html [L]

RewriteRule ^/$ /index-for-all-others.html [L]


# redirect query to Google search

Options +FollowSymlinks

RewriteEngine On

RewriteCond %{REQUEST_URI} .google\.php*

RewriteRule ^(.*)$ ^http://www.google.com/search?q=$1 [R,NC,L]


# deny request according to the request method

RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD)$ [NC]

RewriteRule ^.*$ - [F]


# redirect uploads to a better place

RewriteCond %{REQUEST_METHOD} ^(PUT|POST)$ [NC]

RewriteRule ^(.*)$ /cgi-bin/upload-processor.cgi?p=$1 [L,QSA]


More fun with Redirect 301 and RedirectMatch 301 ^


# seo friendly redirect for a single file

Redirect 301 /old-dir/old-file.html http://domain.com/new-dir/new-file.html


# seo friendly redirect for multiple files

# redirects all files in dir directory with first letters xyz

RedirectMatch 301 /dir/xyz(.*) http://domain.com/$1


# seo friendly redirect entire site to a different domain

Redirect 301 / http://different-domain.com


WordPress Tricks [ ^ ]


Secure WordPress Contact Forms ^


Protect your insecure WordPress contact forms against online unrighteousness by verifying the domain from whence the form is called. Remember to replace the “domain.com” and “contact.php” with your domain and contact-form file names, respectively.


# secure wordpress contact forms via referrer check

RewriteCond %{HTTP_REFERER} !^http://www.domain.com/.*$ [NC]

RewriteCond %{REQUEST_POST} .*contact.php$

RewriteRule .* - [F]


WordPress Permalinks ^


In our article, The htaccess rules for all WordPress Permalinks, we revealed the precise htaccess directives used by the WordPress blogging platform for permalink functionality. Here, for the sake of completeness, we repeat the directives only. For more details please refer to the original article:


If WordPress is installed in the site’s root directory, WordPress creates and uses the following htaccess directives:


# BEGIN WordPress

<IfModule mod_rewrite.c>

 RewriteEngine On

 RewriteBase /

 RewriteCond %{REQUEST_FILENAME} !-f

 RewriteCond %{REQUEST_FILENAME} !-d

 RewriteRule . /index.php [L]

</IfModule>

# END WordPress


If WordPress is installed in some subdirectory “foo”, WordPress creates and uses the following htaccess directives:


# BEGIN WordPress

<IfModule mod_rewrite.c>

 RewriteEngine On

 RewriteBase /foo/

 RewriteCond %{REQUEST_FILENAME} !-f

 RewriteCond %{REQUEST_FILENAME} !-d

 RewriteRule . /foo/index.php [L]

</IfModule>

# END WordPress


Random Tricks [ ^ ]


Activate SSI for HTML/SHTML file types: ^


# activate SSI for HTML and or SHTML file types

AddType text/html .html

AddType text/html .shtml

AddHandler server-parsed .html

AddHandler server-parsed .shtml

AddHandler server-parsed .htm


Grant CGI access in a specific directory: ^


# grant CGI access in a specific directory

Options +ExecCGI

AddHandler cgi-script cgi pl

# to enable all scripts in a directory use the following

SetHandler cgi-script


Disable magic_quotes_gpc for PHP enabled servers: ^


# turn off magic_quotes_gpc for PHP enabled servers

<ifmodule mod_php4.c>

 php_flag magic_quotes_gpc off

</ifmodule>


Enable MD5 digests: ^


Note: enabling this option may result in a relative decrease in server performance.


# enable MD5 digests via ContentDigest

ContentDigest On


Expression Engine Tricks: ^


# send Atom and RSS requests to the site docroot to be rewritten for ExpressionEngine

RewriteRule .*atom.xml$ http://www.yoursite.com/index.php/weblog/rss_atom/ [R]

RewriteRule .*rss.xml$ http://www.yoursite.com/index.php/weblog/rss_2.0/ [R]


# cause all requests for index.html to be rewritten for ExpressionEngine

RewriteRule /.*index.html$ http://www.domain.com/index.php [R]


References



REFERENCES
http://perishablepress.com/press/2006/01/10/stupid-htaccess-tricks/