apache « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ apache ’

Apache : Password Protecting Folders using .htaccess

Posted by on December 27th, 2012

When a user requests a site hosted on apache, Apache first looks for the default file which is generally named “index.html” or “index.php” or something like that in the root directory. We can set/change this order by adding the following directive in the configuration file (present in /etc/apache2/sites-available folder in ubuntu) of the site:

<Directory /var/www/site1/>
    DirectoryIndex index.php index.html first.php
</Directory>

Here /var/www/site1/ is the root directory which contains the site files and folders. We will need to restart apache for the above change to take effect.
Now, apache will first look for a file named “index.php”. If it is found, it will be rendered to the user. If it is not found then apache will look for “index.html” and so on. However, if none of the above listed files are found in the root directory, then apache will simply list all the files and folders present in the root directory.

If the site contains sensitive files, it is not secure to show list of files to every visitor. In that case, we can hide the listing of files and folders by changing the configuration file as:

<Directory /var/www/site1/>
	Options -Indexes
</Directory>

Here, we are simply turning off listing of files and folders by using Options -Indexes. But this is not always the desired scenario. Sometimes, we want to show the directory listing to few users and hide it from others. In that case we can password protect the directory listing such that only authorized users can view the list. Here is how to do it:

1. Create a file named .htaccess in the root directory (if it’s not already there). I created it in /var/www/site1 folder.

2. Insert the following lines into .htaccess file:

 
AuthType Basic
AuthName "Please enter your credentials"
AuthUserFile /var/.htpasswd
Require valid-user

AuthType Basic : It enables the basic authentication

AuthName “Please enter your credentials” : This will appear as a message when user tries to access the directory.

AuthUserFile /var/.htpasswd :

htpasswd is a apache command line utility to create .htpasswd file. If it is not already installed, we can install it by

sudo apt-get install apache2-utils

.htpasswd is the file that will store the usernames and passwords (filename can be anything but it is a good convention to use .htpasswd as filename). We can also create this file inside the root directory of the site (or location of our choice) but the best place to put this file in is /var directory for security reasons. We can create this file by the following command:

htpasswd -c /var/.htpasswd user1

Here we are creating the .htpasswd file and creating a user with username user1. Then it will prompt for password. The password is stored in encoded form.
We can add more users by the following command:

htpasswd /var/.htpasswd user2

Require valid-user : It allows only those users whose entry exists in .htpasswd to login and view the listing.

Now, when the user tries to access the root directory of the site, the following screen will appear:

Cheers!

Raj Gupta
raj.gupta@intelligrape.com
@rajdgreat007

Posted in Linux

Using Apache to save data in redis

Posted by on July 30th, 2012

In one of my projects, I was using redis database to collect some statistics and I thought of saving data into it at apache level. This would considerably enhance the speed of saving data as it would not require the interception of grails to save data.

The first step for this was to install apache by firing the following command in terminal :

sudo apt-get install apache2

After installing apache, it was required to set up a site. For that I created a file named www.raj.com in /etc/apache2/sites-available directory and configured it as follows:

<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName www.raj.com
ServerAlias raj.com

DocumentRoot /usr/lib/cgi-bin

<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride All
AddHandler cgi-script .cgi
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride All
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>

</VirtualHost>

Here the ServerName is set to www.raj.com and DocumentRoot is set to /usr/lib/cgi-bin. It means that if I hit url www.raj.com, then i will see the contents of /usr/lib/cgi-bin directory (This will come into action after enabling the site).
AddHandler cgi-script .cgi means that we are adding a cgi-script handler for files whose extension is cgi.

Now my site is in the list of available sites, but it’s still not enabled. To enable it I fired the following command in terminal :

a2ensite www.raj.com

This command created a soft link of my site into /etc/apache2/sites-enabled directory and now my site was enabled.

The last step was to make an entry for my site in  /etc/hosts. I appended following line to /etc/hosts to do so :

127.0.0.1 www.raj.com

Finally, i was required to reload apache using command

service apache2 reload 

And now my site was live. To save data into the redis database, i created a file named saveData.cgi in /usr/lib/cgi-bin folder, given execution permissions to it and entered the following script into it.


#!/bin/sh
echo "Content-type: text/html\n\n"

date="na"
partnerSite="na"
videoId="na"

date=`echo $QUERY_STRING | sed 's/.*date\=\([^&]\+\).*/\1/'`

partnerSite=`echo $QUERY_STRING | sed 's/.*partnerSite\=\([^&]\+\).*/\1/'`

videoId=`echo $QUERY_STRING | sed 's/.*videoId\=\([^&]\+\).*/\1/'`

`redis-cli hincrby "$videoId-$date-views" $partnerSite 1`

Here shebang is used to execute script in the bash shell and the content type is set to text/html.
In redis, HINCRBY command is used in relation with hashes, where a key has one or more fields each with a corresponding value.
If the key and field already exists in the redis database, HINCRBY command would increment the value of the field by specified number. If the key doesn’t exists, HINCRBY creates a key with specified filed and value.

Thus, if i hit the url http://www.raj.com/saveData.cgi?date=20July2012&partnerSite=facebook&videoId=wwYXWU in my browser, then date, partnerSite and videoId are extracted from the query string using sed command and in the redis database an entry would be saved whose key will be “wwYXWU-20July2012-views”, field will be “facebook” and value will be 1. If the same url is received again, the value of field “facebook” of key “wwYXWU-20July2012-views” will become 2 and so on.

In this way, we can easily use apache to save and update data in redis database.

Posted in Database, Grails, Linux

How to Set-up SSL certificates on your Linux server

Posted by on June 1st, 2012

In one of my project, I have to set-up SSL certificates for my website to make it secure, so that it could also be access via https protocol. SSL is a way to secure internet communication from your browser to a secure website. The websites using SSL will have https:// to their name.

Following are the steps to set-up SSL certificate on your server:
1. Issue Command to Generate Key: openssl genrsa -des3 -out www.MY_DOMAIN_NAME.com.key 2048.
2. Issue Command to Generate CSR(Certificate Signing Request):
openssl req -new -key www.MY_DOMAIN_NAME.com.key -out www.MY_DOMAIN_NAME.com.csr.

This command will prompt for the following X.509 attributes of the certificate:
– Country Name: Use the two-letter code without punctuation for country, for example: US or CA.
– State or Province: Spell out the state completely; do not abbreviate the state or province name, for example: California
– Locality or City: The Locality field is the city or town name, for example: Berkeley. Do not abbreviate. For example: Saint Louis, not St. Louis
– Company: If the company or department has an &, @, or any other symbol using the shift key in its name,the symbol must be spelled out or omitted, in order to enroll. Example: XY & Z Corporation would be XYZ Corporation or XY and Z Corporation.
– Common Name: The Common Name is the Host + Domain Name. It looks like “www.company.com” or “company.com”. etc.
You can skip other attributes by pressing return (or enter)

3. You can verify your CSR (Optional) Here
4. Now, At verilog site or any other site apply for test certificates and fill up the details over there, paste your www.MY_DOMAIN_NAME.com.csr file content on the request form and submit it.
5. After few minutes, You will receive an email which contains the certificate attached in its body, copy that certificate and save it as www.MY_DOMAIN_NAME.com.crt on your server. (For email,check your spam also ;) )
6. Enable MOD-SSL by Issuing Commands: a2enmod ssl
7. Now you need to update the apache config file. Open you sites apache-config file located at /etc/apache2/sites-available/YOUR_SITE_NAME. This is an XML File . Modify “VirtualHost *.80” to “VirtualHost *.443” (443 Port is used for SSL) and paste the following code inside the “VirtualHost *:443” tag.

SSLEngine on
SSLCertificateFile COMPLETE_PATH_TO_CRT_FILE (like /home/user/ssl/www.MY_DOMAIN_NAME.com.crt)
SSLCertificateKeyFile COMPLETE_PATH_TO_KEY_FILE (like /home/user/ssl/www.MY_DOMAIN_NAME.com.key)

– Note: For using both http and https protocol, copy and paste “VirtualHost *.80” tag, modify copied “VirtualHost *.80” to “VirtualHost *.443” (443 Port is used for SSL) and paste the above code inside your “VirtualHost *.443” tag.

7. You can verify your apache config, using the command: apache2ctl configtest
8. Restart apache by issuing command: /etc/init.d/apache2 restart OR apache2ctl restart

Hope it helps.

Regards,
Gautam Malhotra
gautam@intelligrape.com

Posted in Linux, System

Set-up SSL Communication between two Linux servers Using Keytool Command

Posted by on May 31st, 2012

In one of my project, My front end application runs on one server and back end application runs on another. Both application have to communicate with each other through SSL(Secure Sockets Layer). SSL is a way to secure internet communication from your browser to a secure website. The websites using SSL will have https:// to their name.

In comes the Java keytool command, which is a key and certificate management utility. Keytool is a java security tool, which is used to create and manage public keys,private keys,and security certificate. It manages a keystore (database) of cryptographic keys, X.509 certificate chains, and trusted certificates.

Using the Java keytool command you can add the certicate into your keystore as trusted certificate.

Following are the steps to perform https communication between two application on different servers:
1. Copy server1-site.crt file to Server 2.
2. Now, Import this root or intermediate CA certificate to an existing Java keystore, using the command:
    Default keystore password is changeit

keytool -import -trustcacerts -keystore cacerts -storepass YOUR_KEYSTORE_PASSWORD -noprompt -alias webAppCertificate -file www.web-app.mydomain.com.crt

3. Restart apache by issuing command: /etc/init.d/apache2 restart OR apache2ctl restart
4. Repeat, Steps 1 to 3 on server1 with server2-site.crt file.

Using the keytool command you can add , delete ,list certificate from your keystore.

Refrence: http://www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html

Hope it Helps!

Regards,
Gautam Malhotra
gautam@intelligrape.com

Posted in Linux, System

Setting Expires HTTP header on server response through Apache

Posted by on September 13th, 2010

In recent poc, i have set the expires HTTP header on server response for one of the project, such that it will again set when access by user for the specified period, if header is expired already.

The module that control it is “mod_expires.c”. This module is not enabled by default.

You need to enable it by following command (You need to be sudo user):

a2enmod {module name} //here module name is "expires"

Then, open your site configuration file available at apache2/sites-available/{your site}

Append following xml entries in your site configuration file :

<IfModule mod_expires.c>
      <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
          ExpiresActive On
          ExpiresDefault "access plus 2 days"
      </FilesMatch>
</IfModule>

ExpiresDefault Syntax :

ExpiresDefault "{base} [plus] {num  type}*"

Note : Here base is : ‘access’ and the type is : ‘years’, ‘months’, ‘weeks’, ‘days’, ‘hours’, ‘minutes’, ‘seconds’

You can also use “ExpiresByType” for setting different expires for different file type instead of “ExpiresDefault”.

Hope this code will help :)


Regards,
Tarun Pareek
Intelligrape Software

http://in.linkedin.com/in/tarunpareek

Posted in Linux, System

Apache-Tomcat integration on Ubuntu server

Posted by on February 13th, 2008

Follow the steps mentioned below to integrate Apache with Tomcat on an Ubuntu system. The steps assume that Apache and Tomcat are already installed and working fine independently.

  • Install Apache module for tomcat

sudo apt-get install libapache2-mod-jk

  • Create a file by the name “worker.properties” in /etc/apache2 directory. Sample worker.properties file below

workers.tomcat_home=/opt/servers/tomcat5.5
workers.java_home=/opt/java/jdk1.5
ps=/
worker.list=worker1
worker.default.port=8009
worker.default.host=localhost
worker.default.type=ajp13
worker.default.lbfactor=1

  • Add the following line to your site configuration file (/etc/apache2/sites-available/dellServer)

jkMount /* worker1

  • Add the following lines to the end of your /etc/apache2/apache2.conf file

LoadModule jk_module /usr/lib/apache2/modules/mod_jk.so
# Where to find workers.properties
JkWorkersFile /etc/apache2/workers.properties
# Where to put jk logs
JkLogFile /tmp/mod_jk.log
# Set the jk log level [debug/error/info]
JkLogLevel info
# Select the log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
# JkOptions indicate to send SSL KEY SIZE,
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
# JkRequestLogFormat set the request format
JkRequestLogFormat "%w %V %T"

Tags: ,
Posted in Linux, System