October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories

October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Convert the PFX file for Apache

Run the following command using OPENSSL:

1. To export the Private key file from the .pfx file
openssl pkcs12 -in filename.p12  -nocerts -out privatekey.key
2. To export the Certificate file from the .pfx file
openssl pkcs12 -in filename.p12 -clcerts -nokeys -out sslcert.crt

filename.p12 (is your existing IIS PFX file)
privatekey.key (is your new exported private key file)
ssl.crt

3. You now need to copy the  files to the locations as described in the httpd.conf
4. To find out where the files should be copied to run this on the httpd.conf

cat httpd.conf | grep SSLCertificateFile  (this will give you the location of where to copy the certificate file)

cat httpd.conf | grep SSLCertificateKeyFile (this will give you the location of where to copy the key file)

5. You will now need to restart apache

How do I convert a .pfx to be used with an Apache server?

How do I convert my .pfx file to be used with an Apache server?

Answer:

The Apache server will require the following two files:

1 – Server.ker : the private key associated with the certificate
2 – Server.crt :  the public SSL certificate issued by Entrust

Using Open SSL, you can extract the certificate and private key.

To extract the private key from a .pfx file, run the following OpenSSL command:

openssl.exe pkcs12 -in myCert.pfx -nocerts -out privateKey.pem

The private key that you have extract will be encrypted. To unencrypt the file so that it can be used, you want to run the following command:

openssl.exe rsa -in privateKey.pem -out private.pem

The resulting private.pem file should be the key file that you want. Open it up using notepad to make sure there is not additional information showing up as text in the file. There may be some additional lines displaying the DN and Bag Attributes. Remove all of this from the file so that you end up with something like this:

—–BEGIN RSA PRIVATE KEY—–
MjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3
LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp
YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG
A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq
—–END RSA PRIVATE KEY—–

You can now use this as your Server.key file on your Apache Server.

To get the corresponding Server Certificate, you will run the following OpenSSL command:

openssl.exe pkcs12 -in myCert.pfx -clcerts -nokeys -out EntrustCert.pem

You can now use the resulting file as your Server.crt file in Apache.

Convert an OpenSSL (Apache) SSL Certificate to a PKCS12 (Tomcat)

Convert the Key to a PKCS12 Key. This will prompt you for a password which you will need when you change the Tomcat configuration.

openssl pkcs12 -export -in /etc/apache2/ssl.crt/somedomain.com.crt -out somedomain.com.pkcs12 -name “somedomain.com” -inkey /etc/apache2/ssl.key/somedomain.com.com.key

Verify that the pkcs12 file contains your key. You should be able to see your certificate’s common name, and various other parameters.

keytool -list -v -keystore somedomain.com.pkcs12 -storetype pkcs12

Now configure Tomcat by editing conf/server.xml and changing the SSL Connector to something like this:

<connector port="8443" maxThreads="150" acceptCount="100" debug="0" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreType= "PKCS12"
keystoreFile="somedomain.pkcs12"
keystorePass="yourKeystorePass">

Monitoring Bandwidth – Linux

Here is the list of bandwidth monitoring tools for network bandwidth

bmon
bwbar
bwm
bwm-ng
iftop
iperf
ipfm
speedometer
cbm
ibmonitor
pktstat
mactrack
MRTG
Cacti

I think most of the above tools should also be available for other distribution of Linux.

. Here is a link using which bwm-ng can be installed and run on Fedora.

Managing your Linux/Unix log files using logrotate

Log files are one of the most important files where almost all precious and sometimes unnecessary information are stored in regard to your server’s running state. For example, if your system’s security has been breached or compromised, it’s these log files which will come to your rescue to help you identity where or what went wrong.

In case if you don’t know, your Linux/Unix server is currently logging kernel and security logs in the file called /var/log/messages. Just do a simple ” tail -f /var/log/messages ” to get feel and see the actual current logs generated by various daemons running on your system.

Now if your server also has a Apache Web server or a Squid Proxy server running and you want to manage their respective logs in your own fashion, then the following information might help you out.

 

First of all, you will need the program called “logrotate”. Logrotate is very useful utility which can rotate log files and archive them in a location that you specify. We will be using “logrotate” in conjunction with “cron“.

In Linux/Unix, cron is a time-based scheduling service in Unix-like computer operating systems. It is available on almost all versions of Linux and Unix.

Having said that, logrotate should be installed in your Linux/Unix distribution but if is not, simply use your system package management system to install it.

For example, for Debian based system, all you need to do to install logrotate is:

apt-get install logrotate

For this guide, we will be rotating and managing the log files generated by Apache and Squid on a FreeBSD-6.x and a Linux Debian-4.1 box. However, it should be also work on other Linux distributions like RedHat, Slackware or SuSE since the fundamentals are the same of all Linux based distributions.

I also assume that your Apache logs are kept in /var/log/apache and your Squid logs are kept in /var/log/squid.

On a FreeBSD-6.x box:

(1.) Make and Install from ports:

cd /usr/ports/sysutils/logrotate

(2.) Configure and Compile

make install clean

If all goes well, we are done and logrotate is installed.

(3.) Create a new logrotate.conf file.

vi /usr/local/etc/logrotate.conf

# Added the following to rotate Apache and Squid logs

# see “man logrotate” for details
# rotate log files weekly
#weekly
daily

# keep 4 weeks worth of backlogs
rotate 7

# send errors to root
#errors root

# create new (empty) log files after rotating old ones
create

# uncomment this if you want your log files compressed
compress

# RPM packages drop log rotation information into this directory
include /usr/local/etc/logrotate.d

/var/log/lastlog {
monthly
rotate 12
}

# system-specific logs may be configured here

(4.) Create a directory for specific logrotate files

mkdir -p /usr/local/etc/logrotate.d

(5.) First, create a logrotate file for Squid to rotate it’s access.log files for 90 days and cache.log for 7 days.

cd /usr/local/etc/logrotate.d/

vi /usr/local/etc/logrotate.d/squid

#Copy and paste the following

/var/log/squid/access.log {
daily
rotate 90
copytruncate
compress
notifempty
missingok
}
/var/log/squid/cache.log {
daily
rotate 7
copytruncate
compress
notifempty
missingok
}

(6.) Create the necessary directories and files for logrotate and test and debug logrotate

mkdir /var/lib/

touch /var/lib/logrotate.status

/usr/local/sbin/logrotate -d /usr/local/etc/logrotate.conf
/usr/local/sbin/logrotate -f /usr/local/etc/logrotate.conf

(7.) Next, we will rotate and manage Apache logs

vi /usr/local/etc/logrotate.d/apache

#Add the following to rotate and manage Apache access_log and error_log for 30 days.

#Note: If your Apache logs may be in a different directory, simply change the directory.

/var/log/apache/access_log {
daily
rotate 30
copytruncate
compress
notifempty
missingok
}
/var/log/apache/error_log {
daily
rotate 30
copytruncate
compress
notifempty
missingok
}

If all goes well, that’s it. Your Apache and Squid logs should be rotated.

The last thing is to add an entry into crontab and letting the cron daemon rotate your Apache and Squid logs automatically.

(8.) Automating logrotate using crontab

vi /etc/crontab

#Add the following to rotate your logs at 1 AM in the morning

#Logrotate
0 1 * * * root /usr/local/sbin/logrotate /usr/local/etc/logrotate.conf > /dev/null 2>&1

That’s it. Your Apache and Squid logs will be rotating without manual intervention!!

Using logrotate on a Debian-4.1 box

(1.) Install the logrotate program

apt-get install logrotate

(2.) Create the necessary directories and files

mkdir -p /var/lib/logrotate/

touch /var/lib/logrotate/status

mkdir -p /etc/logrotate.d/

(3.) Create a new logrotate.conf

vi /etc/logrotate.conf

#Copy and paste the following

# see “man logrotate” for details
# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones
create

# uncomment this if you want your log files compressed
#compress

# packages drop log rotation information into this directory
include /etc/logrotate.d

# no packages own wtmp, or btmp — we’ll rotate them here
/var/log/wtmp {
missingok
monthly
create 0664 root utmp
rotate 1
}

/var/log/btmp {
missingok
monthly
create 0664 root utmp
rotate 1
}

# system-specific logs may be configured here
(4.) Create the squid logrotate file to rotate and manage access.log for 90 days and cache.log for 7 days.

vi /etc/logrotate.d/squid

#Copy and paste the following

/var/log/squid/access.log {
daily
rotate 90
copytruncate
compress
notifempty
missingok
}
/var/log/squid/cache.log {
daily
rotate 7
copytruncate
compress
notifempty
missingok
}

(5.) Create the Apache logrotate file to rotate and manage access_log for 30 days and error_log for 30days.

vi /etc/logrotate.d/apache

#Copy and paste the following. Note: your apache log’s directory might be different. Simply change the path of your directory.

/var/log/apache/access_log {
daily
rotate 30
copytruncate
compress
notifempty
missingok
}
/var/log/apache/error_log {
daily
rotate 30
copytruncate
compress
notifempty
missingok
}
(6.) Test and debug your logrotate configuration for any errors

/usr/sbin/logrotate -d /etc/logrotate.conf

/usr/sbin/logrotate -f /etc/logrotate.conf

If all goes well, you are good to go.

(7.) Now all that is left is to automate the logrotate process from crontab

vi /etc/crontab

#Copy and paste the following

#Logrotate at 1 AM in the morning

0 01 * * * root /usr/sbin/logrotate /etc/logrotate.conf > /dev/null 2>&1

That’s it! The cron daemon will automatically rotate your Apache and Squid logs at 1 AM on a daily basis.

 

 

To show how you can use logrotate for your own applications, let’s look at an example that will come in handy for a lot of people: rotating logs for your custom virtual hosts. We’ll use apache for this example, but it can be tweaked pretty easily for other web servers like nginx or lighttpd, usually just by changing the postrotate script.

First we’ll want to create a file to hold the configuration that will tell logrotate what to do with the virtual host’s log files. We won’t edit the main config file or the web server’s config file, since there’s always a possibility that a future package upgrade might want to overwrite the config. Instead we’ll make our own. Let’s call it:

/etc/logrotate.d/virtualhosts

This example tosses all the virtual hosts into one file, but if you have one that’s busier than others you may want to create separate config files to handle the needs of your different domains. We’ll also specify several items that are probably already set in your main config, just so we cover all the bases.

The files

We’ll say that we have two virtual domains, domain1.com and domain2.com, and that the log files for each are in /home/demo/public_html/(domain name)/log. The first thing we’ll do in our config file is tell logrotate where to find the log files, then start the config block for them:

/home/demo/public_html/domain1.com/log/*log /home/demo/public_html/domain2.com/log/*log {

If you have more log directories or files to add, just insert them into that list.

Rotate

Next we’ll want to make sure logrotate only keeps as many old logs as we want:

rotate 14

We’ll use 14 in this example to keep two weeks’ worth of logs, but you can of course adjust that number to something suitable to your requirements.

Interval

Now we’ll tell the web server to rotate these logs daily (again, change it if you prefer a longer interval):

daily

Size (optional)

If you prefer a weekly rotation it’s wise to specify a max log size as well, to be on the safe side. The max size setting doesn’t make much difference if you have the logs rotating daily, but if you use “weekly” or longer instead you might also include the line:

size 50M

That way if a log starts getting too large (from unexpectedly heavy traffic, for example) it will be rotated early rather than allowing it to get too unwieldy.

Compression

We’ll specify whether or not we want these logs to be compressed when they’re archived. For this example we’ll use delaycompress to account for the graceful restart of apache, which means we also need to turn compression on:

compress
delaycompress

Sharedscripts

You might have several virtual hosts, and that would mean several logs to rotate. To make sure the web server only gets restarted after all the rotations are done we add:

sharedscripts

Postrotate

We’ll specify a postrotate script that will restart the web server:

postrotate
        /usr/sbin/apache2ctl graceful > /dev/null
endscript

And finally, we close the config block with a curly bracket:

}

The whole shebang

Once we bring it all together our config file will look like this:

/home/demo/public_html/domain1.com/log/*log /home/demo/public_html/domain2.com/log/*log {
        rotate 14
        daily
        compress
        delaycompress
        sharedscripts
        postrotate
                /usr/sbin/apache2ctl graceful > /dev/null
        endscript
}

You’ll want to test that, of course, either by making sure you’re watching things when the nightly cron jobs are run, or by running logrotate right now:

/usr/sbin/logrotate /etc/logrotate.conf

If you don’t get any errors back you should be okay. But if you want to be absolutely certain you can run through some of the tests we would use when we suspect something isn’t working right.

Testing logrotate

If you suspect logrotate is having some trouble, or you just want to make sure a new config you’ve put in place will work, there are some useful flags you can pass to logrotate when you run it from the command line:

Verbose

The verbose flag, “-v”, tells logrotate to say what it’s doing while it’s doing it. It’s very useful when trying to find out why logrotate doesn’t rotate a log when you want it to.

Debug

The debug flag, “-d”, tells logrotate to go through the motions of rotating logs but not actually rotate them. It can be handy if you want to test a new config file but don’t want any actual log rotation run when you do (if you’re working on a production server, for example).

The debug flag is good for checking that the config file is formatted properly and that logrotate can find the log files it would rotate. However, since it doesn’t actually run the rotations it doesn’t test some parts of the process like the postrotate scripts.

Force

The force flag, “-f”, forces logrotate to rotate all logs when it runs, whether or not they would normally need to be rotated at that time. If you want to thoroughly test logrotate’s configs this is the flag to use. Just remember that logrotate will be rotating logs and deleting old ones according to the configuration you’ve set up, so don’t accidentally rotate out a recent log you needed to keep.

The force flag can be useful if you’re convinced that logrotate should be rotating a log, but it isn’t. Forcing the issue will help you tell if the problem is that logrotate doesn’t think the log needed rotating (if you run with the force flag and the log is rotated), or if the problem is that logrotate isn’t able to affect the log file (if you run it and nothing happens to the log).

Note that if logrotate is set to add a date to the name of an archived log, not even using the force flag will get logrotate to make a new archive in the same day (since the name it would use for the archive is already taken). In that circumstance you may need to rename the most recent archive (for each log file in a given config block) before you can force a log rotation.

Combining flags

The testing flags can be used together quite effectively. To have logrotate tell you what it would do if you made it rotate everything, but not actually rotate anything, you can combine all three:

/usr/sbin/logrotate -vdf /etc/logrotate.conf

You’ll get treated to a long list of things logrotate would do, including which log files it would rotate and what it would do during that process.

If you then want to test all the rotate configs in their entirety — including the scripts run after rotations — you can run logrotate without the debug flag:

/usr/sbin/logrotate -vf /etc/logrotate.conf

All the logs will be rotated, and skimming the output should help you catch any obvious problems. You’ll also want to make sure that all your services are still running okay (that there was nothing wrong with the postrotate scripts), and that all the logs actually did get rotated.

How logrotate remembers

If you find that a log isn’t rotating even though it’s old enough that it should, a simple approach to fixing the problem is to manually run logrotate with the “-f” flag. But if you’re the sort who wants to know why something’s gone wrong there’s one more file you can check before forcing a rotation:

/var/lib/logrotate/status

That file is where logrotate stores information about when it last rotated each log file. If you look inside that file you’ll see something like:

logrotate state -- version 2
"/var/log/acpid.log" 2010-6-18
"/var/log/iptables.log" 2010-6-18
"/var/log/uucp.log" 2010-6-29
...

It’s a straightforward format – the log file location is on the left, and the date when it was last rotated is on the right. Sometimes it can happen that the dates on your server get a little wonky (if you were tinkering with an NTP service or the like), and the date when a log was last rotated winds up being a future date. If that’s happened you’ll see it here.

If you want to check logrotate out with a particular log file but don’t want to force everything to rotate, you can delete the log’s entry from the logrotate status file. Then when you run logrotate normally, it should create a new entry for the log with today’s date (even though it may not actually rotate the log – it uses that first run as a baseline if it’s just interval-based).

Summary

For something that runs quietly in the background and only really performs one type of task, logrotate does quite a bit. You hopefully understand logrotate better than you wanted to. At the least you should be able to set up new logrotate config files for your own purposes, either creating them from scratch or copying existing configs and modifying them appropriately. And most importantly, you can keep your logs from getting out of control.

 

 

Logrotate is a great utility to manage and adminster log files in a system. It provides you with a lot of options, namely, automatic rotation, compression and mailing of log files. Each log file can be rotated hourly, daily, weekly or monthly. In this article, I will show you how to manage your log files using logrotate.

Any type of logs can be managed using logrotate. It runs as a daily cron job. These days most of the operating systems come with logrotate pre-installed so you probably won’t have to deal with the installation. Lets start with looking at the files and directories used by logrotate.

Files and Directories used by Logrotate

The 2 important files in case of logrotate are

/etc/logrotate.conf

/var/lib/logrotate.status    or    /var/lib/logrotate/status

The first file is where the whole configuration and default options of logrotate is stored. The second file contains the information about the last rotation times of different log files.

The directory thats usually used by logrotate is

/etc/logrotate.d

The options specified in /etc/logrotate.conf are used as default for rotating and managing log files. But if we want to specify separate settings for a set of log files then we can add their config files in this directory /etc/logrotate.d. Although we can even use another directory to save config files by changing an option in /etc/logrotate.conf.

Now, enough of the theory lets see how these config files really look and what all the different options in it mean.

Logrotate Options

Let me first show you some commonly used options of logrotate and then we will see how to configure various options in the config file.

rotate <num> Log files are rotated “num” times before getting deleted or mailed.
daily When used this means log files should be rotated daily
weekly Log files should be rotated weekly
monthly Log files should be rotated monthly
notifempty Don’t rotate the log if its empty
compress Compress the files after rotating them
delaycompress This options means to delay the compression of a log file to the next rotation cycle. This is used in combination with compress.
missingok If the log file is missing, go on to the next one without issuing an error message.
create <mode> <owner> <group> After rotation create a new empty file with the following properties. e.g create 640 root adm. Just “create” will ensure to inherit the properties of previous log files.

Logrotate config files

As stated above, /etc/logrotate.conf is where the default options to handle logs are specified. A typical log file will look something like this.

# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones
create

# uncomment this if you want your log files compressed
#compress

# packages drop log rotation information into this directory
include /etc/logrotate.d

# no packages own wtmp, or btmp — we’ll rotate them here
/var/log/wtmp {
    missingok
    monthly
    create 0664 root utmp
    rotate 1
}

/var/log/btmp {
    missingok
    monthly
    create 0660 root utmp
    rotate 1
}

The options mentioned in the config file above means that the logs are going to be rotated “weekly” and only 4 copies of backlogs will be maintained. On every rotation “create” a new empty file with properties inherited from the previous logs. Compression of backlogs is disabled.

The “include” directive is used to mention the directory in which the package specific log config files will be saved.

Managing Package specific log files in /etc/logrotate.d

Now, if there is an application which generates logs how would it be able to use logrotate to control and manage its logs. This is all done using its /etc/logrotate.d directory. This is where applications drop the information required by logrotate to manage their logs. e.g consider the example of apache logs. My apache logrotate config file looks something likes this (its /etc/logrotate.d/apache2).

/var/log/apache2/*.log {
    weekly
    missingok
    rotate 5
    compress
    delaycompress
    notifempty
    create 640 root adm
    sharedscripts
    postrotate
        if [ -f “`. /etc/apache2/envvars ; echo ${APACHE_PID_FILE:-/var/run/apache2.pid}`” ]; then
            /etc/init.d/apache2 reload > /dev/null
        fi
    endscript
}

Now, cross checking  the options from the table mentioned above the following properties of the logs can be inferred.

  • Its going to be a weekly rotation
  • 5 backlogs will be maintained in compressed format. But since we are using ‘delaycompress’ as well, the compression of a backlog will take place in the next rotation.
  • No rotation will take place if file is empty.
  • No error in case no log is found.
  • On every rotation a new file will be created with owner root, group adm and permission 640

We haven’t discussed anything about ‘sharedscripts’ or ‘postrotate’ yet. Lets begin with prerotate/endscript and postrotate/endscript.

Prerotate and Postrotate

Both of these options control the scripts that will need to be run either before or after rotating a log file. Lets take the above example.

postrotate
        if [ -f “`. /etc/apache2/envvars ; echo ${APACHE_PID_FILE:-/var/run/apache2.pid}`” ]; then
            /etc/init.d/apache2 reload > /dev/null
        fi
endscript

‘endscript’ is mandatory to be mentioned in both prerotate and postrotate to specify the ending of the script.

You would have also noticed the sharedscripts option in the apache2 logrotate config file. Now, ifsharedscripts options is not specified, prerotate and postrotate will run the scripts on each log file which is rotated. But if you look carefully at the file logs mentioned in the apache2 logrotate conf file, its a wild card /var/log/apache2/*.log i.e. not just a single file but a bunch of files matching a pattern. These files in our case will be /var/log/apache2/access.log and error.log. So, for every rotation we will have 2 log files.

But look at the script that we want to run after rotation. It reloads the apache server and there is probably no need to run this script twice. So, by using sharedscripts we are ensuring that the script doesn’t run on every rotated log file but only once.

htaccess

Forbidding access:


Setting a password:


Redirections:

Frequent errors:

Programs list for managing of the Apache servers

 

What is .htaccess for?

When you type an address in the address bar of your browser, your computer receives files that your browser displays. The web server controls which files and how should be displayed (sent) to you. The two most popular servers are IIS and Apache.

Like any other software, a web server has certain settings. However, as an Apache user, you may have no (and if we talk about virtual hosting, most probably you will have no) rights to change the Apache configuration using its main configuration files that affect all server users. But you can modify some configuration files that affect only your website. One of such files is .htaccess.

It is a flexible Apache web server configuration file. “Flexible” means that as soon as you modify anything in this file, the changes are applied immediately. You can use it to redefine a lot of directives from the file httpd.conf (this file is the main configuration file in Apache and it affects absolutely all users of this Apache copy). In those cases when you have no access to the Apache configuration file (exactly in case of virtual hosting), it is this file that will help you.

A web user cannot access this file using the browser. If the .htaccess file is located in the root directory of the server, it affects the entire server except those directories where other .htaccess files are stored (and except all their subdirectories).

Example:

Your directories have the following structure on the server:

The directories ‘user1’ and ‘user2’ will be subdirectories for the user directory. If we put the .htaccess file in the ‘user’ directory, it will automatically affect directories ‘user1’ and ‘user2’.

We save another .htaccess file to the ‘data’ directory, this file is different from the one stored in the ‘user’ directory. The .htaccess file located in ‘data’ will affect the directories ‘data1’ and ‘data2’.

Now we save another .htaccess file that is different from the one stored in the directory 2 levels higher (the ‘user’ directory) to the ‘user2’ directory. As a result, the settings of the ‘user2’ directory will be defined only by the .htaccess file located in this directory.

Since most often Apache is configured in such a way that it always searches each directory for this file, .htaccess will help you quickly reconfigure the server without stopping it.

.htaccess syntax

Here is the required syntax. If you do not observe it, it will result in server errors.

—  paths to files (directories) are specified from the server root. Example: /opt/home/www.site.com/htdocs/config/.htpasswd
—  domains with protocols specified. Example: Redirect / http://www.site.com

The file name is exactly “dot” htaccess. It must be in the UNIX format (ASCII mode).

How to forbid visitors to read files from a directory?

Forbidding all files:

deny from all

Allow access from a certain IP address:

order allow deny
deny from all
allow from <your_IP>

In this case, <your_IP> stands for a specific address. For example:

order allow deny
deny from all
allow from 192.126.12.199

Forbid access from a certain IP address:

order allow deny
deny from all
deny from <your_IP>

Using <your_IP> is similar to the example above.

Forbidding a group of files by mask:

<Files ~ "\.(inc|sql|...other_extensions...)$">
  order allow,deny
  deny from all
</Files>

Defines access to a file by its extension. For example, forbidding web visitors to access files with the “inc” extension:

<Files ~ "\.(inc)$">
  order allow,deny
  deny from all
</Files>

In this example the Apache server can access files with this extension.

Forbidding a particular file:

You can forbid a particular file using its name and extension.

<Files config.inc.php>
  order allow,deny
  deny from all
</Files>

This example forbids the file config.inc.php to be accessed.

Setting a password

Password for a directory:

AuthName "Private zone"
AuthType Basic
AuthUserFile /pub/home/your_login/.htpasswd
require valid-user

AuthName will be displayed for the user and can be used to explain authentication request. The value of AuthUserFile defines the location where the file with passwords for accessing this directory is stored. This file is created by a special tool named htpasswd.exe or more convenient and flexible program Htpasswd Generator.

For example, we create the following .htaccess file in the protected directory:

AuthName "For Registered Users Only"
AuthType Basic
AuthUserFile /pub/site.com/.htpasswd
require valid-user

In this example, the user requesting this directory will read the message “For Registered Users Only”, the file with passwords for access must be stored in the directory /pub/site.com/ and it must be named .htpasswd . The directory is specified from the server root. If you specify the directory incorrectly, Apache will not be able to read the .htpasswd file and nobody will get access to this directory.

Password for one file only:

Similar to protecting a whole directory with a password, you can set a password for one file only. An example of setting a password to the file private.zip:

<Files private.zip>
  AuthName "Users zone"
  AuthType Basic
  AuthUserFile /pub/home/your_login/.htpasswd
</Files>

Password for a group of files:

Similarly, you can use <Files ~ "\.(inc|sql|...other_extensions...)$"> to set password for files by mask. An example of setting a password for accessing all files with the “sql” extension:

<Files ~ "\.(sql)$">
  AuthName "Users zone"
  AuthType Basic
  AuthUserFile /pub/home/your_login/.htpasswd
</Files>

Checking access rights

Task: there is a directory named a1 containing two subdirectories (a2, a3), there are two access levels for users. The first group can access only a1 and a2, the second group can access all three directories. You should perform authentication only once – when accessing a1, but observe access rights for ?2 and ?3.
The username and password are requested only once while accessing ?1 – if the user has access to ?2, the password it not requested again. If the user has no access to ?3, he will see the message “Enter the password”.

www.site.com/a1
www.site.com/a1/?2
www.site.com/a1/a3

a1 – common and protected at the same time
?2 and ?3 only for certain users.

The .htaccess file for the directory ?1:

AuthName "Input password"
AuthType Basic
AuthUserFile "/pub/home/your_login/htdocs/closearea/.htpasswd"
<Files *.*>
  require valid-user
</Files>

The .htaccess file for the directory ?2:

AuthName "Input password"
AuthType Basic
AuthUserFile "/pub/home/your_login/htdocs/closearea/.htpasswd"
<Files *.*>
  require user user1 user2 user3
</Files *.*>

The .htaccess file for the directory ?3:

AuthName "Input password"
AuthType Basic
AuthUserFile "/pub/home/your_login/htdocs/closearea/.htpasswd"
<Files *.*>
  require user user1 user4 user5
</Files *.*>

How to redirect a visitor?

Redirecting to another URL:

To redirect a visitor to http://site.com, add the following to .htaccess

Redirect / http://www.site.com

Displaying different pages depending on the visitor’s IP address:

SetEnvIf REMOTE_ADDR <required_IP> REDIR="redir"
RewriteCond %{REDIR} redir
RewriteRule ^/$ /another_page.html

For example, redirecting visitors with IP 192.12.131.1 to the page about_my_site.html:

SetEnvIf REMOTE_ADDR 192.12.131.1 REDIR="redir"
RewriteCond %{REDIR} redir
RewriteRule ^/$ /about_my_site.html

Redirecting a visitor when he request certain pages:

It is already for all network viruses and scanners. Now any request with the address /_vti_bin will be automatically redirected to Microsoft:

redirect /_vti_bin http://www.microsoft.com
redirect /scripts http://www.microsoft.com
redirect /MSADC http://www.microsoft.com
redirect /c http://www.microsoft.com
redirect /d http://www.microsoft.com
redirect /_mem_bin http://www.microsoft.com
redirect /msadc http://www.microsoft.com
RedirectMatch (.*)\cmd.exe$ http://www.microsoft.com$1

How to change the default page?

To change the page that will be displayed when a visitor access a directory, write:

DirectoryIndex <necessary page>

It is possible to specify several pages:

DirectoryIndex index.shtml index.php index.php3 index.html index.htm

How to make Apache process SSI directives?

SSI allows you to “assemble” a page using its parts. You have the code of the menu in one part, the code of the header in another part and the footer in a third part. And the visitor sees a usual page consisting of the code stored in your parts.

Some settings in httpd.conf are required.

Add Includes to the Options directive in the block starting with <Directory/> and ending with </Directory>.

After that add the following to the .htaccess file:

AddHandler server-parsed .shtml .shtm .html .htm

If you want to use some kind of GUI for managing Apache server and do all these manipulations easily (using the special wizards and managers) then we advise you to use the program ApacheConf

How to process Apache errors yourself?

The most interesting and useful Apache errors are 403-404, 500.

403 – the user has not been authenticated, access denied (Forbidden).
404 – the requested document (file, directory) is not found.
500 – internal server error (for example, an error in the syntax of the .htaccess file).

For the user to see your own error messages for these error, add the following to .htaccess:

ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html

If error 404 occurs, the user receives the file errors/403.html.

It is convenient to create your own handler for some errors. Add the following to .htaccess:

ErrorDocument 403 /errors/error.php?403
ErrorDocument 404 /errors/error.php?404
ErrorDocument 500 /errors/error.php?500

Determine the document that caused error in error.php using $HTTP_SERVER_VARS[‘REQUEST_URI’] and process it then. If .htaccess contains the file with the full path for ErrorDocument (http://site.com/error.php), $HTTP_SERVER_VARS[‘REQUEST_URI’] will contain this file instead of the one that caused the error.

Internet Explorer 5.0 incorrectly processes the error file if it is smaller than 1 kilobyte. It opens the standard IE 404 page.

How to forbid the contents of a directory to be displayed if it has no index file?

Suppose all graphics used on your site is stored in the ‘img’ directory. A visitor can type the address of this directory in his browser and see the list of all your image files. Of course, it will not cause any damage, but you might forbid the visitor to view this directory as well. Add the following to .htaccess:

Options -Indexes

Is it possible to specify the encoding of all file the browser receives documents in by default?

When the Internet only came to existence and first browsers appeared, it often happened that the browser could not automatically determine which of the Russian encodings a document was written in and the browser displayed a complete mess. To avoid it, specify that all pages will be encoded in Windows-1251:

AddDefaultCharset windows-1251

Is it possible to specify the encoding of uploaded files?

When a visitor uploads a file to the server, it is possible to recode it. To do it, specify that all uploaded files will be encoded in Windows-1251:

CharsetSourceEnc windows-1251

Frequent errors

I created the .htaccess file, but the server returns 500 – Internal Error

There is an error in its syntax or the file is saved in the wrong format. See this question.

What programs do exist for managing of the Apache server

There are several programs for tuning and controlling the Apache servers.

The most powerful Graphical User Interface (GUI) for Apache server tuning has ApacheConf. ApacheConf is a shell (GUI) for configuring Apache web servers that will help you to tune the main configuration httpd.conf file. ApacheConf presents all the information in the httpd.conf file in a structured view. All of the server’s directives are grouped by category (Global directives, Directories, Virtual hosts, etc) and all these groups are represented as a tree. In this way,you can see the entire structure of the server at a glance and you can easily manage all of the server’s directives, as well as the directories and virtual hosts.

Also we advise you to to use Apache Commander.

And of course Htpasswd Generator for managing your users, user groups and their passwords

OpenSSL Commands

General OpenSSL Commands

These commands allow you to generate CSRs, Certificates, Private Keys and do other miscellaneous tasks.

    Generate a new private key and Certificate Signing Request

    openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout privateKey.key

    Generate a self-signed certificate (see How to Create and Install an Apache Self Signed Certificate for more info)

    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privateKey.key -out certificate.crt

    Generate a certificate signing request (CSR) for an existing private key

    openssl req -out CSR.csr -key privateKey.key -new

    Generate a certificate signing request based on an existing certificate

    openssl x509 -x509toreq -in certificate.crt -out CSR.csr -signkey privateKey.key

    Remove a passphrase from a private key

    openssl rsa -in privateKey.pem -out newPrivateKey.pem

Checking Using OpenSSL

If you need to check the information within a Certificate, CSR or Private Key, use these commands.

You can also check CSRs and check certificates using our online tools.

Check a Certificate Signing Request (CSR)

  openssl req -text -noout -verify -in CSR.csr

 Check a private key

openssl rsa -in privateKey.key -check

Check a certificate

openssl x509 -in certificate.crt -text -noout

Check a PKCS#12 file (.pfx or .p12)

openssl pkcs12 -info -in keyStore.p12

Debugging Using OpenSSL

If you are receiving an error that the private doesn’t match the certificate or that a certificate that you installed to a site is not trusted, try one of these commands. If you are trying to verify that an SSL certificate is installed correctly, be sure to check out the SSL Checker.

Check an MD5 hash of the public key to ensure that it matches with what is in a CSR or private key

openssl x509 -noout -modulus -in certificate.crt | openssl md5
openssl rsa -noout -modulus -in privateKey.key | openssl md5
openssl req -noout -modulus -in CSR.csr | openssl md5

Check an SSL connection. All the certificates (including Intermediates) should be displayed

openssl s_client -connect www.paypal.com:443

Converting Using OpenSSL

These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software.

For example, you can convert a normal PEM file that would work with Apache to a PFX (PKCS#12) file and use it with Tomcat or IIS. Use our SSL Converter to convert certificates without messing with OpenSSL.

Convert a DER file (.crt .cer .der) to PEM

openssl x509 -inform der -in certificate.cer -out certificate.pem

Convert a PEM file to DER

openssl x509 -outform der -in certificate.pem -out certificate.der

Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM

openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes

You can add -nocerts to only output the private key or add -nokeys to only output the certificates.

Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)

openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt

The following commands allow you to generate CSRs, Certificates, Private Keys and other tasks.

Generate a new private key and matching certificate signing request (Unix)

openssl req -out CSR.csr -pubkey -new -keyout privateKey.key

Generate a new private key and matching certificate signing request (Windows)

openssl req -out CSR.csr -pubkey -new -keyout privateKey.key -config .\share\openssl.cmf

Generate a certificate signing request for an existing private key

openssl req -out CSR.csr -key privateKey.key -new

Generate a certificate signing request based on an existing x509 certificate

openssl x509 -x509toreq -in MYCRT.crt -out CSR.csr -signkey privateKey.key

Decrypt private key

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privateKey.key -out certificate.crt

Remove a passphrase from a private key

openssl rsa -in privateKey.pem -out newPrivateKey.pem

Checking commands

Use the following commands to check the information within a Certificate, CSR or Private Key. You can also check CSRs and certificates using our online tools.

Check a certificate signing request

openssl req -text -noout -verify -in CSR.csr

Check a private key

openssl rsa -in privateKey.key -check

Check a certificate

openssl x509 -in certificate.crt -text -noout

Check a PKCS#12 keystore

openssl pkcs12 -info -in keyStore.p12

Debugging commands

If you are receiving certificate errors, try one of the following commands to debug a SSL connection. Use our Site Check as well to check the certificate.

Check the MD5 hash of the public key

openssl x509 -noout -modulus -in certificate.crt | openssl md5
openssl rsa -noout -modulus -in privateKey.key | openssl md5
openssl req -noout -modulus -in CSR.csr | openssl md5

Check an SSL connection. All certificates (also intermediates) should be shown

openssl s_client -connect https://www.paypal.com:443

Converting commands

Use the following commands to convert certificates and keys to different formats to make them compatible with specific types of servers or software. For example, convert a normal PEM file that would work with Apache to a PFX (PKCS#12) file for use with Tomcat or IIS.

Convert DER (.crt .cer .der) to PEM

openssl x509 -inform der -in certificate.cer -out certificate.pem

Convert PEM to DER

openssl x509 -outform der -in certificate.pem -out certificate.der

Convert PKCS#12 (.pfx .p12) to PEM containing both private key and certificates

openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes
    add -nocerts for private key only; add -nokeys for certificates only

Convert (add) a seperate key and certificate to a new keystore of type PKCS#12

openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt

Enable SSL in Tomcat

Step 1
Windows[goto Command]
%JAVA_HOME%\bin\keytool -genkey

Enter all the details which keytool is going to prompt. (rememeber the password)

once you done, please go to your [USER_HOME](document & settings), locate the .keystore.

Copy this file and paste in tomcat root folder.

Step 2
Open [tomcat_home]/conf/server.xml

uncomment the SSL config entry. And configure the SSL certificate info.[see beloe]
<Connector port=”8443″ protocol=”HTTP/1.1″ SSLEnabled=”true”
maxThreads=”150″ scheme=”https” secure=”true”
clientAuth=”false” sslProtocol=”TLS” keystoreFile=”.keystore” keystorePass=”12345678? />

Step 3
Start tomcat
[tomcat_home]/bin/start-up.bat
in tomcat console you will see a message
INFO: Initializing Coyote HTTP/1.1 on http-8443

Now open a new browser and type https://localhost:8443/.

TOMCAT TUNING

  1. tuning rules Doesn’t compensate for bad, slow or poorly written applications
  2. If you allocate memory more than 3g, preferably divided into multiple tomcat young generation can not be set too much, minor gc will stop the world.
  3. Three factors negatively impact Tomcat’s performance more than any others – network delays, remote client latency, and application architecture.

    Two of these factors – network delays and remote client latency – are for the most part unavoidable, although using a web server in front of Tomcat to serve static content will free up more power for dynamic content.

    Remote client latency can be mitigated by compressing content with Apache mod_zip or Tomcat’s compression filter.

  4. ulimit-n 8192

  5. logging

    logging is ok, but it will:

    • Catch-all logger goes to stdout and file
    • No overflow protection
    • Synchronized logging

    In linux turn off console handler.so we can:

     Remove logging to stdout-no rotation.modify logging.properties, and remove ConsoleHandler as follows: . Handlers = 1catalina.org.apache.juli.FileHandler 
  6. Our tuning options

    • Threads

      MaxThread – Max number of concurrent requests, can be set to 400, if the cpu load is very low added value, if the load is high, decrease it.

    • Keep alive requests

      HTTP KeepAlive is a good thing, but Wasted server resources, thread idle while others waiting to be serviced. Https handshake is very expensive, you can use the keepalive MaxKeepAliveRequests – max number of requests to serve before closing, can not be set too large, too large thread the idle too much, but can not provide the service in highly concurrent environments, to close off KeepAlive is set to 0. spring tc server recommended setting is 15.

    • TCP Backlog (acceptCount)

      Represents nr of additional connections the OS should accept on your behalf, Useful when Tomcat can’t accept connections fast enough, Typical ranges 50-300. Peak period declined more servers to increase this value.

    • connectionTimeout

      His following meanings:

      • Values from 2000-60000
      • Represents the SO_TIMEOUT value
      • Essentially, max time between TCP packets during a blocking read or write
      • Critical to a stable system
      • Also used for keep alive timeout ConnectionTimeOut – max time to keep thread open default 20s this value is too high for a web server in terms of reasonable setting, according to the application scenario. The recommended value is 3000, Increase if Working with slow clients (dial up) or Using a layer 7 load balancer with connection limit / pool and keep alive on.
  7. Different connectors

    • BIO-Blocking Java connector, default
    • The APR-Uses native C code for IO Overall very good, especially ssl, try using this model
    • NIO-Non blocking Java connectors
  8. Dynamic content

    No way in tomcat level cache, can use jsp cache to cache content like blocking mode of the Tomcat has to deliver it, Worker thread is not the released The until all content has been delivered, Changing the connector wont change behavior

  9. Static content

    • The tomcat providing Size based cache, default 10mb, for BIO-Tomcat has to deliver it blocking mode
    • NIO / APR, Tomcat can use SEND_FILE, Release worker thread, deliver the content using a background thread when the client is ready to receive, Increases concurrency
  10. Do not use the AJP protocol

  11. JVM TUNING

    Key parameters for JVM tuning

    • Memory

      Total heap: -Xms/-Xmx

      Used to define size of Java heap Aim to set as low as possible Setting too high can cause wasted memory and long GC cycles 
    • Control of the new generation:-XX: Xmn

      Size eden + the New gen displayed in the survivor space. With The jmap-heap different. Increasing the young generation will reduce the size of the old generation. Value impact on system performance, Sun official recommended configuration for the entire heap of 3/8, do not use jdk1.4 previous parameter XX: XX NewSize: NewRatio , according to the case of the test, 3/8 is still relatively large, set at about 30% more appropriate. Setting too high or too low leads to inefficient GC. Too big, minor gc will stop the world, too small, too often.

    • Garbage collection

       -XX: MaxGCPauseMillis This parameter can not do not use very dangerous set too short to gc spend a lot of effort to reach their goals, resulting in decreased throughput. -XX: + UseConcMarkSweepGC -XX: + CMSIncrementalMode -XX: + CMSIncrementalPacing -XX: CMSIncrementalDutyCycleMin = 0 -XX: CMSIncrementalDutyCycle = 10 -XX: + UseParNewGC -XX: + CMSPermGenSweepingEnabled 

      Note that last this CMSPermGenSweepingEnabled, in jdk1.6 after cms collector can be achieve permgen recycling, especially for groovy such dynamically generated class and the program loaded.

  12. gc log:

    -Verbosegc-XX: + PrintGCTimeStamps-XX: + PrintGCDetails-Xloggc: gc.log

21 Apache Tomcat Configuration Tips

Tip #1 – Watch Out for White Space

When installing Tomcat under Windows, the path to the installation directory should not contain white space. The default (c:/Program Files) is not acceptable, because it contains a white space character. Installing under “C:/ProgramFiles” is acceptable because this path does not contain any white space characters.

Tip #2 – Check The System Variables

Regardless of the operating system that Tomcat is installed under, the installer should check the system variables to make sure they are set correctly. In particular, CATALINA_HOME should be set to Tomcat’s installation directory.

Tip #3 – Set Username and Password for Tomcat Manager

If you are using the Tomcat Manager, set a username and password. Set this username’s role to “manager,tomcat”.

Tip #4 – Read the Log Files

By default, Tomcat’s log files are stored in the CATALINA_HOME/log directory. Use them to solve a myriad of problems.

Tip #5 – Configuring the Admin Web Application

If you are using the admin webapp that comes with Tomcat, make sure the path specified in the docBase attribute of the Context element is absolute, not relative. The admin context can be specified in admin.xml (for auto deployment) or server.xml.

If you are not using the admin webapp, delete admin.xml.

Tip #6 – The Admin Webapp vs. the Manager Webapp

The manager webapp that comes with Tomcat is a scaled-down, simplified version of the admin webapp. The Manager webapp lets you install new webapps on a non-persistent basis for testing, and also allows you to stop, reload, remove, or undeploy webapps. For better security, use manager rather than admin wherever possible.

Tip #7 – Two Options For Deploying a WAR File

If you have a WAR file, you can deploy it by simply copying it into CATALINA_BASE/webapps. When Tomcat notices the new WAR file sitting there, it will unpack the file into the appropriate subdirectory and create a context for it. The context it creates is defined in the DefaultContext element in server.xml.

If it is not appropriate to use the default context, create a context fragment for the webapp, put it in a file named x.xml (where x is the name of your webapp), and put the file into CATALINA_BASE/webapps. The webapp itself can then be stored anywhere on the filesystem.

In either case, you can deploy your webapp without editing server.xml and without restarting Tomcat. One caveat: Do not turn off liveDeploy.

Tip #8 – Configure Virtual Hosts in server.xml

Your test environment can be set up as a virtual host by adding a host element to the engine element in server.xml. Don’t forget to create the appropriate DNS entry, too.

Tip #9 – When Usage Increases, Balance the Load

Tomcat provides several load balancing techniques that allow requests to be spread across multiple servers. See also the following link: http://people.apache.org/~markt/presentations/2009-04-01-TomcatTuning.pdf

Tip #10 – Implement Custom Error Pages

Default error pages do not give the end users useful information. Create your own error pages and give the end users meaningful messages.

Tip #11 – Use a Logging Toolkit

Eliminate System.err and System.out from application code. Use a logging toolkit (e.g., Log4J) instead.

Tip #12 – Create Users to Access the Manager Webapp

If you plan to use the manager webapp, the default configuration won’t help you much because there are no users with the manager role. Add the manager role and at least one user who has the manager role in CATALINA_HOME/conf/tomcat-users.xml.

Tip #13 – Filter by IP or Host

If only certain machines are allowed to access your webapp, create a valve to let only those machines in. Specify the machines by IP address or hostname.

Tip #14 – Strip Down server.xml

Remove comments, connectors, and any other components you don’t need from server.xml to make the file more readable. However, since comments can be important, keep a copy of the original file around for future reference.

Remove

<Connector port=”8009? enableLookups=”false” redirectPort=”8443? protocol=”AJP/1.3?></Connector>

from server.xml if you are using standalone Tomcat (i.e., without the Apache server).

Tip #15 – Thread Pool

If using multiple CPUs, raising the thread pool above the default 250 may prove beneficial. On the other hand, reducing the thread count may be beneficial if your server is running slowly.

Tip #16 – Compress Network Traffic

Use the compression and compressableMimeType attributes of the connector element to configure GZIP compression and to specify the MIME types that should be compressed.

Tip #17 – Production Logging

Tomcat’s default configuration creates duplicate log files. Remove duplicate logging in .handlers (in logging.properties).

Tip #18 – Rotate The Tomcat Log Files

This example rotates log files. Adjust the values to suit your environment.

1catalina.java.util.logging.FileHandler.pattern = ${catalina.base}/logs/catalina.%g.log

1catalina.java.util.logging.FileHandler.limit = 20000000

1catalina.java.util.logging.FileHandler.count = 5

Tip #19 – Use Clustering With Load Balancing

When balancing the load between multiple Tomcat instances, if an instance fails, another instance can seamlessly take over its sessions if clustering is configured. Without clustering, a failing instance’s sessions will crash.

Tip #20 – Disable the Shutdown Port

Turn off Tomcat’s default shutdown port by setting the port attribute to -1 in the server element. This makes it impossible to shut down Tomcat via IP:port. Shutdown will only be possible by a kill command issued by the user who owns the Tomcat instance.

Tip #21 – Ignore Interfaces That Are Not Required

Connectors listen to all interfaces by default. Use the address attribute of the connector element to force the connector to ignore all interfaces that are not used by your webapp.