Sunday 11 November 2012

Optimize a Linux VPS with Apache and PHP

Apache Optimization

 To start, open the Apache configuration file and finding the directives section. On a cPanel server, it will be located in /usr/local/apache/conf/. On a Plesk server, it will be in /etc/httpd/conf/. If you are using vi or vim: once you open the file, you can find the directives by scrolling through the file, or by typing forward-slash ‘/’ and typing the exact string that you are looking for (search is case specific).

[root@host /] vim /usr/local/apache/conf/httpd.conf
or
[root@host /] vim /etc/httpd/conf/httpd.conf
This list is a composite of the settings we will be reviewing from fresh install on a cPanel server:
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
MinSpareServers 5
MaxSpareServers 10
StartServers 5
MaxClients 150
MaxRequestsPerChild 0



Timeout
Timeout 300
Usually this value doesn’t require editing and a default of 300 is sufficient. Lowering the ‘Timeout’ value will cause a long running script to terminate earlier than expected.
On virtualized servers like VPS servers, lowering this value to 100 can help improve performance.

KeepAlive
KeepAlive On
This setting should be “On” unless the server is getting requests from hundreds of IPs at once.
High volume and/or load balanced servers should have this setting disabled (Off) to increase connection throughput.

MaxKeepAliveRequests
MaxKeepAliveRequests 100
This setting limits the number of requests allowed per persistent connection when KeepAlive is on. If it is set to 0, unlimited requests will be allowed.
It is recommended to keep this value at 100 for virtualized accounts like VPS accounts. On dedicated servers it is recommended that this value be modified to 150.

KeepAliveTimeout
KeepAliveTimeout 15
The number of seconds Apache will wait for another request before closing the connection. Setting this to a high value may cause performance problems in heavily loaded servers. The higher the timeout, the more server processes will be kept occupied waiting on connections with idle clients.
It is recommended that this value be lowered to 5 on all servers.

MinSpareServers
MinSpareServers 5
This directive sets the desired minimum number of idle child server processes. An idle process is one which is not handling a request. If there are fewer spareservers idle then specified by this value, then the parent process creates new children at a maximum rate of 1 per second. Setting this parameter to a large number is almost always a bad idea.
Liquidweb recommends adjusting the value for this setting to the following:
Virtualized server, ie VPS 5
Dedicated server with 1-2GB RAM 10
Dedicated server with 2-4GB RAM 20
Dedicated server with 4+ GB RAM 25
MaxSpareServers
MaxSpareServers 10
The MaxSpareServers directive sets the desired maximum number of idle child server processes. An idle process is one which is not handling a request. If there are more than MaxSpareServers idle, then the parent process will kill off the excess processes.
The MaxSpareServers value should be set as double the value that is set in MinSpareServers.

StartServers
StartServers 5
This directivesets the number of child server processes created on startup. This value should mirror what is set in MinSpareServers.

MaxClients
MaxClients 150
This directive sets the limit on the number of simultaneous requests that will be served. Any connection attempts over the specified limit will be queued. Once a process is freed at the end of a different request, the queued connection will then be served.
For virtualized servers such as VPS accounts, it is recommended to keep this value at 150. For all dedicated servers the recommended value for this setting is 250.
MaxRequestsPerChild
MaxRequestsPerChild 0
This directive sets the limit on the number of requests that an individual child server process will handle. After the number of requests reaches the value specified, the child process will die. When this value is set at 0, then the process will never expire.
Liquidweb recommends adjusting the value for this setting to the following:
Virtualized server, ie VPS 300
Dedicated server with 1-4GB RAM 500
Dedicated server with 4+GB RAM 1000

 you would need to run the distiller after editing the httpd.conf file:
/usr/local/cpanel/bin/apache_conf_distiller --update
=======================================================================================
 

cPanel PHP Optimization / Hardening


You can  start customizing the php configuration file, that’s php.ini.
or
 From cPanel WHM navigate to: Main >> Service Configuration >> PHP Configuration Editor
And click on “Switch to Advanced Mode”.
Now configure it as bellow:
# You should change the memory limit value with what suits your needs
memory_limit 64M
register_globals off
# You should change the uload max filesize value with what suits your needs
upload_max_filesize 64M
upload_tmp_dir /tmp
display_errors off
# This option may cause problems for badly written scripts
allow_url_fopen off
session.save_path /tmp
magic_quotes_gpc off
 
 Navigate to: Main >> Security Center >> PHP open_basedir Tweak
Make sure “Enable php open_basedir Protection.” is enabled and click “Save”.
 

 

 
 

Monday 29 October 2012

Add Multiple shared IPs in WHM

First, you need to create a /var/cpanel/mainips/ directory, if it doesn’t exist:

mkdir /var/cpanel/mainips/
 
Then, create a /var/cpanel/mainips/root file, with the following content:

1.2.3.4
3.4.5.6
 
Basically, each line is an additional shared IP in WHM. That’s it!

Sunday 28 October 2012

Change main shared IP of cpanel server

You can setup your main shared IP from

WHM >> Main >> Server Configuration >> Basic cPanel/WHM Setup >> Main Shared Virtual Host IP

and you can see your ip address usage from :

WHM >> Main >> IP Functions >> Show or Delete Current IP Addresses

Sunday 21 October 2012

Invalid kernel, or some kernel modules are not loaded

#vzlist -a | grep IP
ID         -stopped   IP   servername

#vzctl start ID

Invalid kernel, or some kernel modules are not loaded
Container start failed (try to check kernel messages, e.g. “dmesg | tail”)

 The first thing you need to check is if vz service is functional OR not. To start, use command as below.

 /etc/init.d/vz start
All the containers/VPS will start one by one.
It might be that vz service is not set to On when server boots. You can check it with command as below.
chkconfig –list | grep vz
If it’s set to Off, you need to switch it On with command below.
chkconfig on vz

Sunday 7 October 2012

Hide the Apache Version via httpd.conf

Open your httpd.conf file using text editor such as vi:
   
vi httpd.conf

 Append/modify config directive as follows:

ServerTokens ProductOnly
ServerSignature Off

 Save and close the file. Restart Apache web server:

 # /etc/init.d/httpd restart

Hiding Apache server versions and OS details via Webmin

These simple steps will help you if you use Webmin

1. Log into Webmin
2. From the navigation onthe left click on "Servers"

3. Click on "Apache Webserver" from expanded list
4. Click on "Global configuration" tab
5. Click on the "Miscellaneous" icon
6. From "Server HTTP header" option, select: Product only.

7. Click "Save"
8. Then from the top right corner of the next screen click "Apply Changes" to make the changes live.

Monday 1 October 2012

How to Enable and Disable Website Maintenance Mode in plesk

If Maintenance mode is swich on, your site may offline. You may get error similar to code error like 'Calling LoadLibraryEx on ISAPI filter'  when view site through a browser.

You can view this error "Maintenance mode is swich on, your site may offline"  near the domain name under 'Websites and domain'  section on plesk contrl panel.


To switch on the maintenance mode for a website to suspend a site temporarly:
  1. Go to the Websites & Domains tab.
  2. Click Website Maintenance Mode (in the Advanced Operations group).
  3. If you have several websites, locate the site you want to temporarily suspend, and click the corresponding Manage link.
  4. Select the Switch on the maintenance mode for website checkbox.
  5. Click OK.
If the custom error documents option is switched on for the site, then you can edit the "503 Service Temporarily Unavailable" document to include your own text




To switch off the maintenance mode and put a site back online:
  1. Go to the Websites & Domains tab.
  2. In the list of your websites, locate the website you want to put back online. It should be accompanied by the Switched off for maintenance status indicator.
  3. Click the corresponding Change link.
  4. Clear the Switch on the maintenance mode for website checkbox.
  5. Click OK.


Sunday 30 September 2012

Download and Install GIT

cd /usr/local/src
 
>> download the GIT
wget http://kernel.org/pub/software/scm/git/git-1.7.6.tar.bz2
 
>> Next, extract the downloaded file.
tar xvfj git-1.7.6.tar.bz2
cd git-1.7.6
 ./configure
 make
 make install
 

Enabling Railo on a domain using Tomcat

>> Go to the directory: /opt/railo/tomcat/conf (This is the default install directory     we run on servers for Railo)

>>  Edit the file: server.xml

>>  Go to the line where it has commented code and has: HOST ENTRY TEMPLATE

>>  Enter new lines after the commented code with the following replacing domain.com with your domain and the docBase with the path on your server to your public_html or wwwroot or httpdocs:

<Host name="domain.com" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
<Context path="" docBase="/home/username/domain.com" />
<Alias>www.domain.com</Alias>
</Host>

>> Save the  server.xml file

>>  Now you need to restart Railo

 /etc/init.d/railo_ctl restart

>>  Allow a up to 30 seconds for the service to restart and then try going to your Railo web administrator example below:

http://www.domain.com/railo-context/admin/web.cfm

>> You can access this URL using the default password of railo server admin. You can view this default password by login to 

 http://IP/railo-context/admin/server.cfm  and  go to Password under the section 'Security' .

>> Once you login to the railo web admin page of the domain using this default password, you can reset password there.

Disable cfexecute in the coldfusion server

Enabling cftags will cause many security issues in the server especially in a shared server.

 We can disable cftags like CFEXECUTE and CFREGISTRY on ColdFusion Server as follows:

For ColdFusion Standard Edition
Open the ColdFusion Administrator
Browse to Security and Select Resource Security
Click on the CF Tags tab at the top
Select CFEXECUTE, CFREGISTRY, and any other unused tags
Click the right arrow to move the tags to the disabled column
Click 'Finish' to save changes

Directory index forbidden by Options directive

tail -f  /usr/local/apache/logs/error_log   
shows error Directory index forbidden by Options directive


Make sure that following line present in your .htaccess file

Options +Indexes

 will fix this issue.

DATABASE ERROR: CONNECTION FAILED! when login to roundcube

issue: when login to webmail via RoundCube getting this error

=====================
DATABASE ERROR: CONNECTION FAILED!

Unable to connect to the database!
Please contact your server-administrator.
=====================

solution:
Try the following proceedures.
>> Repairing the database 'roundcube'.
>>  Running the command /usr/local/cpanel/bin/update-roundcube --force will also help
>>  Last try /scripts/upcp --force

check suphp enabled from shell

run

/usr/local/cpanel/bin/rebuild_phpconf --current

Can't remove an ip address

issue: When go to
WHM -> IP Functions -> Show or Delete Current IP Addresses and click a Remove l it shows removed and
then i check again .The ip is still there


Fix: Remove it from /etc/ips - if it's not in there, you probably have to remove the configuration file for it in /etc/sysconfig/network-scripts/ifcfg-XXXX where XXXX is the device it is bound to, then down the device using:

ifconfig XXXX down

Awstat for parked domain ??

Main and parked, both domains load from public_html folder and the awstats for main domain include the parked domain visits as well.
So the separate  awstat for parked domain is not possible.

Create an Instant Alias from WebsitePanel

Login to WebsitePanel
Click on Configuration -> Virtual Servers
Click on My Server Resources
Click on Instant Alias and enter your main domain after customerdomain.com.maindomain.com
Click on Update button
Click on Configuration -> Servers
Click on My Server
Click on Instant Alias and enter your main domain after customerdomain.com.maindomain.com
Click on Update button

php website not working and always opens like a download

Use the following code in .htaccess file :

 AddHandler application/x-httpd-php .html .htm
 
And try to access the link.

php extension issue

If you need to view only php file with extension .php   not with  .php.* , add this code in .htaccess file


<FilesMatch "\.(php.)">
ForceType 'text/plain'
</FilesMatch>

Hide php extension in the URL

Write this code in the .htaccess file to hide php extension , like so:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ /$1.php [L,QSA]

Saturday 29 September 2012

lib mysql client error or php relocation error

"It may appear as wordpress pages of a site are seems to be dislocated.

Sometimes a  blank page or an internal server error seen in browser when access the site may also due to php relocation error. As there are lot of other reasons for showing blank page and internal server error, it can be check as a final check for these errors ".

>> Error shows in apache error log may like this.
# tail -f /usr/local/apache/logs/error_logs

php: symbol zlibVersion , version libmysqlclient_16 not defined in in file libmysqlclient.so.16 with link time reference. Instead php: relocation error: php: symbol zlibVersion the error could be php: relocation error: php: symbol crc32.

This is an example and the issue could happen with any shared library not only with libmysqlclient.so .
Just follow these steps to fix this issue.
 nm /usr/lib64/libmysqlclient.so.16.0.0 | grep zlibVersion

The output is:
00000034c60d64b0 T zlibVersion

Now just remove the current link

 rm -f /usr/lib64/mysql/libmysqlclient.so.16
  and create a new one with the library that contains the symbol

  ln -s /usr/lib64/libmysqlclient.so.16.0.0 /usr/lib64/mysql/libmysqlclient.so.16

 This should resolve the case, and the php: symbol zlibVersion , version libmysqlclient_16 not defined in in file libmysqlclient.so.16 with link time reference error was solved.


Redirection from http to https and viceversa using htaccess file

Redirect from http to https
=========================
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]


Redirect from https to http
======================
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{SERVER_PORT} ^443$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]

Script to remove a particular file from all folders

/home/user/public_html]# find . -iname test.php -exec rm -f {} \;
which will remove all test.php files from all folders under public_html directory

change permission of all files and folders

Just run following commands after login to the server via ssh as root.

[/home/user/public_html]# find . -type f -exec chmod 0644 {} \;      // To change permission for all files under public_html directory to 644

[/home/user/public_html]# find . -type d -exec chmod 0755 {} \;     // To change permission for all directories under public_html directory to 755

Redirect to another domain without the url changing

To frame forward "domain1/file1.html" to "domain2/file2.html" put the following information in your file1.html file:

<HTML>
<HEAD>
<TITLE>domain1</TITLE>
</HEAD>
<FRAMESET ROWS="*,0">
<FRAME SRC="http://domain2/file2.html" NORESIZE>
<NOFRAMES>
Your browser does not support frames.
</NOFRAMES>
</FRAMESET>
</HTML>

Allow root account to use SSH

Allowing direct root access over ssh is a security risk. However following steps will allow you to login as root over ssh session:


Open sshd_config file:
# vi /etc/ssh/sshd_config
Find out line that read as follows:
PermitRootLogin no
Set it as follows:
PermitRootLogin yes

 Find out line that read as follows:
 DenyUsers root user2 user3

 Set is as follows:
 DenyUsers user2 user3

 Save and close the file. Restart the sshd:
 # /etc/init.d/ssh restart

Enable or disable local mail delivery on a cPanel server



If you have WHM access. 

  1. Click Edit DNS Zone.
  2. Select the domain you are working with and click Edit.
  3. Scroll to the bottom of the Edit DNS Zone screen.
  4. Do one of the following:
    • Select Local Mail Exchanger to enable local mail delivery.
    • Select Remote Mail Exchanger to disable local mail delivery.

Tuesday 3 January 2012

Shell Script Programs.

2.Back up of all database

#!/bin/bash
export DB_BACKUP="/usr/local/bin/backup"
export DB_USER="root"
export DB_PASSWD="123"


echo ""
echo "Backup and rotate all mysql databases"
echo "--------------------------"

rm -rf $DB_BACKUP/04
mv $DB_BACKUP/03 $DB_BACKUP/04
mv $DB_BACKUP/02 $DB_BACKUP/03
mv $DB_BACKUP/01 $DB_BACKUP/02
mkdir $DB_BACKUP/01


echo "* Creating backup..."
mysqldump --user=$DB_USER --password=$DB_PASSWD --all-databases | bzip2 > $DB_BACKUP/01/mysql-`date +%Y-%m-%d`.bz2
echo "----------------------"
echo "Done"





3.CHANGE CASE FROM UPPER TO LOWER AND LOWER TO UPPER

#!/bin/bash
echo "enter"
echo "1 for uppercase"
echo "2 for lowercase"
read n
echo "enter file name"
read file
#for file in `ls`
if [ -f $file ]
then
if [ $n = 1 ]
then
up=`echo $file | tr '[ a-z ]' '[ A-Z ]'`
#if [ $up != $file ]; then
mv -i $file $up
fi

if [ $n = 2 ]
then
lc=`echo $file | tr '[ A-Z ]' '[ a-z ]'`
#if [ $up != $file ]; then
mv -i $file $lc
fi

#mv $file `echo $file | tr '[ a-z ]' '[ A-Z ]'`
fi



3.APPLICATION OF GETOPTS



#!/bin/bash
#myops()
#{
#  echo "Usage: $0 -h -c -e"
#  echo "Options: These are optional argument"
#  echo " -h help on how to use this script"
#  echo " -c wishes based on time"
#  echo " -e search and delete the file "filename" from the located path "
#  echo " their values are not taken)"
#  exit 1
#}

helps()
{
echo "This command is used to check valid command line argument are passed to script. Usually used in while loop.
Syntax:
getopts {optsring} {variable1}

getopts is used by shell to parse command line argument.

examlpe:
We have script called ani which has syntax as
ani -n -a -s -w -d
Options: These are optional argument
    -n name of animal
    -a age of animal
    -s sex of animal
    -w weight of animal
    -d demo values (if any of the above options are used their values are not taken)"
}

wish()
{
temp=`date +%H`
#temp=`date | cut -c12-13`
echo $temp
if [ $temp -lt 12 ]
then
echo "Good morning"
#fi
elif [ $temp -ge 12 -a $temp -lt 16 ]
then
echo "Good afternoon"
#fi
elif [ $temp -ge 16 -a $temp -lt 20 ]
then
echo "Good evng"
#fi
#if [ $temp -gt 20 ]
#then
else
echo "Good ni8"
fi
}

del()