Categories

Nginx Tomcat installation configuration

Tomcat is a lightweight application server, in the small and medium-sized system and concurrent access to the user is not a lot of occasions are widely used, is the development and debugging JSP program of choice. It can be argued that when a Tomcat server is configured on a machine, it can use it to respond to requests for HTML pages. In fact Tomcat is part of the Nginx server extension, but it is run independently, so when you run tomcat, it actually runs as a separate process with Nginx.

Install tomcat

Tomcat installation is divided into two steps: install the JDK and install Tomcat.

The JDK (Java Development Kit) is a product of Sun Microsystems for Java developers. Since the introduction of Java, JDK has become the most widely used Java SDK. JDK is the core of the entire Java, including the Java runtime environment, Java tools and Java-based class library. So in order to run the jsp program must have JDK support, of course, the premise is to install Tomcat JDK installed.

Install the JDK

Download JDK

cd /usr/local/src/

Download JDK official website:

http://www.Oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

rpm -ivh jdk-7-linux-i586.rpm

vim /etc/profile

JAVA_HOME=/usr/java/jdk1.7.0_45

JRE_HOME=/usr/java/jdk1.7.0_45/jre

PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin

CLASSPATH=:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib

export JAVA_HOME JRE_HOME PATH CLASSPATH

[root@localhost ~]# source /etc/profile

[root@localhost ~]# echo $PATH

java -version

Install Tomcat

cd /usr/local/src/

wget http://www.aminglinux.com/bbs/data/attachment/forum/apache-tomcat-7.0.14.tar.gz

If you think this version is not suitable, you can go to the official website (http://tomcat.apache.org/) download.

tar zxvf apache-tomcat-7.0.14.tar.gz

mv apache-tomcat-7.0.14 /usr/local/tomcat

cp -p /usr/local/tomcat/bin/catalina.sh /etc/init.d/tomcat

vim /etc/init.d/tomcat

Add the following in the second line:

# chkconfig: 112 63 37

# description: tomcat server init script

# Source Function Library

. /etc/init.d/functions

JAVA_HOME=/usr/java/jdk1.7.0_45

CATALINA_HOME=/usr/local/tomcat

After saving the file, do the following:

chmod 755 /etc/init.d/tomcat

chkconfig –add tomcat

chkconfig tomcat on

Start tomcat:

service tomcat start

To see if the boot is successful:

ps aux | grep tomcat

If there is a process, please enter http: // IP: 8080 in the browser / you will see the main interface tomcat.

tomcat

1. Configure the access port for the tomcat service

tomcat default is activated 8080, if you want to modify to 80, you need to modify the server.xml file:

vim /usr/local/tomcat/conf/server.xml

turn up:

tomcat:

service tomcat stop

service tomcat start

tomcat

tomcat

vim /data/tomcatweb/app.jsp

Now time is: <%=new java.util.Date()%>

[root@localhost ~]# curl -xlocalhost:80 www.rmohan.com/app.jsp

Now time is: Thu Jun 13 15:26:03 CST 2013

tomcat connection mysql database:

cat jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/rmohan?useUnicode=true&characterEncoding=utf-8

jdbc.username=WordPress

jdbc.password=WordPress

hibernate.dialect=org.hibernate.dialect.MySQLDialect

hibernate.show_sql=false

hibernate.format_sql=true

hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider

hibernate.cache.use_query_cache=true

hibernate.schemaUpdate=false

Nginx configuration all jsp pages are handled by tomcat:

server {

listen 80;

server_name rmohan.com www.rmohan.com;

index index.html index.jsp;

root /home/www/rmohan/rmohan;

rewrite ^/(.*)$ https://www.rmohan.com/$1 permanent;

location ~ /\. { access_log off; log_not_found off; deny all; }

location ~* (\.jsp)|(\.do)$ {

include proxy.conf;

proxy_pass http://127.0.0.1:8080;

}

location /rmohan {

root /home/www/rmohan;

include proxy.conf;

proxy_pass http://127.0.0.1:8080;

}

}

server {

listen 443 ssl;

server_name rmohan.com www.rmohan.com;

index index.html index.jsp;

root /home/www/rmohan/rmohan;

ssl on;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

#ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA;

#ssl_prefer_server_ciphers on;

#ssl_dhparam /etc/pki/tls/private/dhparam.pem;

ssl_certificate /etc/pki/tls/certs/rmohan.com.crt;

ssl_certificate_key /etc/pki/tls/private/rmohan.com.key;

#ssl_session_tickets off;

#ssl_session_timeout 1d;

#ssl_session_cache shared:SSL:1m;

add_header Strict-Transport-Security ‘max-age=31536000’; # remember the certificate for a year and automatically connect to HTTPS for this domain

location ~ /\. { access_log off; log_not_found off; deny all; }

location ~* (\.jsp)|(\.do)$ {

include proxy.conf;

proxy_pass http://127.0.0.1:8080;

}

location /rmohan {

root /home/www/rmohan;

include proxy.conf;

proxy_pass http://127.0.0.1:8080;

}

}

Tomcat

vi /usr/local/tomcat/conf/server.xml +71

rsync + inotify

rsync + inotify is a more commonly used real-time synchronization solution, but it is not applicable in all the scenes,

rsync + inotify more suitable for the following 10 small-scale web cluster in real-time synchronization, but in the use of rsync + inotify solution and the use of rsync daily,
rsync + inotify rsync server needs to deploy multiple and only one client, rsync client as a daily content of the server so that it will push the data to each Each rsync on the server.
Which used to monitor the file system changes the tool is inotify-tools, rsync client installed inotify-tools after the need to specify the file path to be monitored, the path under the monitored file changes can be used according to the relevant information Triggers rsync to make file push. Linux support inotify kernel minimum 2.6.13, you can use uname-r can view, now CentOS 5 are supported above are more than 2.6.18 so the kernel is generally supported.
Installation is also very simple, after the configuration of the epel source can be installed through yum: yum-y install inotify-tools, after the installation of two binary files are inotifywait and inotifywatch, which is used to monitor the file changes is inotifywait, and inotifywait the parameters used by the option is also very simple:

-m is to keep monitoring changes.
-r Use the recursive form to monitor the directory.
-q Reduce redundant information and only print out the required information.
-e Specifies the list of events to be monitored.
–timefmt is the output format for the specified time.
–format Specifies the details of the file changes.

So you can use the script to hang in the background real-time monitoring specified directory file used to trigger rsync to do file push:

/usr/local/scripts/rsync_inotify.sh &

#!/bin/bash
#rsync_inotify.sh
port=873
src_dir=”/data/www/”
rsyncd_user=”username”
rsyncd_host=”192.168.2.1″
DEST_name=”backup”
password_file=”/etc/.rsync.passwd”

inotifywait -mrq –timefmt ‘%Y-%m-%d %H:%M:%S’ –format ‘%T %Xe %w%f’ -e modify,delete,create,attrib ${src_dir} | while read line
do
file=$(echo $line | awk ‘{print $4}’)
dir=$(dirname $file)
if [ -f $file ];then
rsync -vzrLtopg –progress –delete –port=${port} ${file} –password-file=${password_file} ${rsyncd_user}@${rsyncd_host}::${DEST_name}
else
cd $dir && rsync -vzrLtopg –progress –delete –port=${port} ./ –password-file=${password_file} ${rsyncd_user}@${rsyncd_host}::${DEST_name}
fi
done

Basic ClamAV installation on CentOS 7 and CentOS 6

Basic ClamAV installation on CentOS 7 and CentOS 6

ClamAV is an open source antivirus engine for detecting trojans, viruses, malware & other malicious threats. ClamAV includes a multi-threaded scanner daemon, command line utilities for on demand file scanning and automatic signature updates.
It is one of the most popular virus scanner that run on CentOS and RedHat and here is very simple quick installation steps.

CentOS 7 Installation
1. ClamAV can easily be installed on CentOS 7.x or RHEL 7.x system to use Fedora EPEL repo. Here is how to add them to you CentOS 7
# wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm
# rpm -ivh epel-release-7-5.noarch.rpm
2. Install ClamAV and all prerequisites
# yum install clamav-server clamav-data clamav-update clamav-filesystem clamav clamav-scanner-systemd clamav-devel clamav-lib clamav-server-systemd
3. Now lets remove Example lines from configuration files.
#sed -i -e “s/^Example/#Example/” /etc/freshclam.conf

#sed -i -e “s/^Example/#Example/” /etc/clamd.d/scan.conf
4. Run ClamAV updates
# freshclam
6. Run your scan.
#clamscan –infected –remove –recursive /home
7. For testing purposes you can upload test virus and make sure it is detected.
#curl -O http://www.eicar.org/download/eicar.com
clamscan –infected –remove –recursive
CentOS 6 Installation
1. Install EPEL repo for CentOS 6
#wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
#rpm -Uvh epel-release-6*.rpm
2. Install ClamAV
#yum install clamav clamd
3. Start ClamV services and make sure they set to auto start
#clamd on
#chkconfig clamd on
#clamd start
Below is example of how to run scan against home directory and moving infected files to /usr/local/virusBAD/
#clamscan -ir /home -l /var/log/clamscan.log –move=/usr/local/virusBAD/

Enable Event MPM in Apache 2.4 on CentOS/RHEL 7

Apache apache, Event, Modules, MPM 2 Comments

Apache MPM (Multi-Processing Modules) are Apache modules for creating child processes in Apache. There are many Apache MPM available, Each of them works in his own way. If you are using default Apache installation, Apache will use Prefork MPM by default.

Event MPM is launched with many improvements from worker MP. I prefer to use the Event MPM which is an improvement over the Worker MPM. Event MPM is that Event has a dedicated thread which handles all Keep Alive connections and requests.

This article will help you to Disable Prefork MPM and Enable Event MPM on Apache 2.4 running on your Linux operating system.

Enable Event MPM in Apache

First edit Apache MPM configuration file in your favorite text editor.

# vim /etc/httpd/conf.modules.d/00-mpm.conf
Comment LoadModule line for mpm_prefork_module, mpm_worker_module and Un comment LoadModule line for mpm_event_module in configuration as per showing below.

#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
#LoadModule mpm_worker_module modules/mod_mpm_worker.so

LoadModule mpm_event_module modules/mod_mpm_event.so

enable event mpm

After making above changes just restart your Apache servers.

# systemctl restart httpd
Check Active MPM in Apache

Now you have successfully enabled Event MPM in your Apache server. To verify current MPM enabled on your server use following command.

[root@TecAdmin ~]# httpd -V | grep MPM

Server MPM: event

Open Web Application Security Project

In today’s article we will guide you through the process of installing mod_security with the OWASP (Open Web Application Security Project) core rule set on a CentOS 7 from source.

ModSecurity is a web application firewall engine that provides very little protection on its own. In order to become useful, ModSecurity must be configured with rules. In order to enable users to take full advantage of ModSecurity out of the box, Trustwave’s SpiderLabs created the OWASP ModSecurity Core Rule Set (CRS) Project. Unlike intrusion detection and prevention systems, which rely on signatures specific to known vulnerabilities, the CRS provides generic protection from unknown vulnerabilities often found in web applications, which are in most cases custom coded.

Prerequisites

Log in to your your server as user “root” user credentials and make sure that all packages are up to date. You can make use of below command to update your CentOS 7 server.

# yum -y update
After system update install the following dependencies as ModSecurity 2.x works only with Apache 2.0.x or higher. Let’s run below command to install apache and its other dependencies as shown below.

# yum install gcc make httpd-devel libxml2 pcre-devel libxml2-devel curl-devel git
system prereq

Installing mod_security

Get the ‘mod_security’ source package to install on your server from their official website link .mod_security can be installed in most web servers like Nginx, Apache and even Microsoft IIS. But in this tutorial will cover only on a server running Apache.

#cd /opt/
#wget https://www.modsecurity.org/tarball/2.9.1/modsecurity-2.9.1.tar.gz
mod security

Extract the downloaded archive and change the current working directory to the newly extracted directory using below commands.

#tar xzfv modsecurity-2.9.1.tar.gz
#cd modsecurity-2.9.1
Now, using below commands configure, compile and install mod_security from the source code as shown shown.

#./configure
# make install
installing mod_security

Configure mod_security

After installation setup of mod_security, copy recommended configuration files.

# cp modsecurity.conf-recommended /etc/httpd/conf.d/modsecurity.conf
# cp unicode.mapping /etc/httpd/conf.d/
Now we need to configure the Apache web server . Open the web server configuration file and add the following lines in it.

# vim /etc/httpd/conf/httpd.conf
LoadModule security2_module modules/mod_security2.so
LoadModule unique_id_module modules/mod_unique_id.so
Save the changes using ‘:wq!’ and restart Apache services.

# systemctl restart httpd.service
# systemctl status httpd.service
# systemctl enable httpd.service
mod_security configurations

Installing OWASP

Now we will install OWSAP CRS to be integrated with Apache’s ModSecurity. Use below commands to download and configure OWASP (Open Web Application Security Project) core rule set for a base configuration.

# cd /etc/httpd
# git clone https://github.com/SpiderLabs/owasp-modsecurity-crs.git
#mv owasp-modsecurity-crs modsecurity-crs
#cd modsecurity-crs
#cp modsecurity_crs_10_setup.conf.example modsecurity_crs_10_config.conf
Now once again open the Apache configuration file to add the following lines at the end.

#vim /etc/httpd/conf/httpd.conf
LoadModule security2_module modules/mod_security2.so
LoadModule unique_id_module modules/mod_unique_id.so
So now you’ve installed Mod_Security and OWASP-CRS, it’s time to restart Apache service so the module can be loaded along with its rules.

# systemctl restart httpd.service
OWASP setup

Enjoy some basic necessary protection on your Linux CentOS 7 Apache server. It gives you couple of other advantages like below.

Real-time Blacklist Lookups: utilizes 3rd Party IP Reputation
Web-based Malware Detection: identifies malicious web content by check against the Google Safe Browsing API.
Identification of Application Defects: alerts on application misconfigurations.
HTTP Denial of Service Protections: defense against HTTP Flooding and Slow HTTP DoS Attacks.
Tracking Sensitive Data: Tracks Credit Card usage and blocks leakages.
Trojan Protection: Detecting access to Trojans horses.
Integration with AV Scanning for File Uploads – detects malicious files uploaded through the web application.
Error Detection and Hiding: Disguising error messages sent by the server.
Common Web Attacks Protection: detecting common web application security attack.
Automation Detection: Detecting bots, crawlers, scanners and other surface malicious activity.
HTTP Protection: detecting violations of the HTTP protocol and a locally defined usage policy.

Conclusion

mod_security is basically used to protect and monitor real time HTTP traffic and web applications from brute fore attacks and it also acts as intrusion detection and prevention system for web applications. In order to become useful, ModSecurity must be configured with rules which we can then use OWASP (Open Web Application Security Project) which is a Core Rules Set (CRS) for mod_security base configuration. Thank you for reading this and I hope you find this article useful.

MOD_REWRITING AN ENTIRE SITE

Using mod_rewrite to redirect all pages to one central PHP page’.

On my site, I decided to use an all-index structure, as that’s how I prefer to do things – it means that the scripting language is more hidden from the end user than if you linked to pages such as “something-bizarre.jsp” and means that if the scripting language used to create the pages was changed the names of the pages wouldn’t have to be.
In using mod_rewrite to modify an entire website, the following points needed to be addressed:

Images and CSS files should not be rewritten
Since the only subdomain used by the site is ‘www’, if the user does not enter it then it should be added automatically and visibly for them.
All versions of a webpage should be automatically and visibly rewritten to a single URL. i.e. ‘www.example.com/somepage/’, ‘example.com/somepage/’, ‘www.example.com/somepage’ and ‘example.com/somepage’ should all resolve to ‘www.example.com/somepage/’
Once all visible rewriting has been completed, the URL should be invisibly redirected to a master page which is able to interpret the URL which the user requested and serve up the correct content.
The following is what I came up with. Please refer to “mod_rewrite, a beginner’s guide (with examples)” if you need any extra pointers as to what anything means.

###################################################
# Turn the RewriteEngine on. #
###################################################

RewriteEngine on

###################################################
# Add a leading www to domain if one is missing. #
###################################################
# If this rule is used, the rewriting stops here #
# and then restarts from the beginning with the #
# new URL #
###################################################

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

###################################################
# Do not process images or CSS files further #
###################################################
# No more processing occurs if this rule is #
# successful #
###################################################

RewriteRule \.(css|jpe?g|gif|png)$ – [L]

###################################################
# Add a trailing slash if needed #
###################################################
# If this rule is used, the rewriting stops here #
# and then restarts from the beginning with the #
# new URL #
###################################################

RewriteCond %{REQUEST_URI} ^/[^\.]+[^/]$
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [R=301,L]

###################################################
# Rewrite web pages to one master page #
###################################################
# /somepage/ => master.php #
# ?page=somepage #
# /somesection/somepage => master.php #
# ?section=somesection #
# &page=somepage #
# /somesection/somesub/somepage/ #
# => master.php #
# ?section=somesection #
# &subsection=somesub #
# &page=somepage #
###################################################
# Variables are accessed in PHP using #
# $_GET[‘section’], $_GET[‘subsection’] and #
# $_GET[‘page’] #
###################################################
# No more processing occurs if any of these rules #
# are successful #
###################################################

RewriteRule ^([^/\.]+)/?$ /master.php?page=$1 [L]
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ /master.php?section=$1&page=$2 [L]
RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ /master.php?section=$1&subsection=$2&page=$3 [L]

USING VLOGGER TO SPLIT APACHE LOGS

Vlogger is a program that handles large amounts of virtualhost logs and splits it to separate files.
This is a short HOWTO to configure it using Apache.

Install vlogger in debian etch
# aptitude install vlogger
Make sure you have working Apache server

Configuring vlogger
Change the LogFormat line (there are multiple LogFormat lines – in this example we will change the one that is named combined) in /etc/apache2/apache2.conf. We must add the string %v at the beginning of it

vi /etc/apache2/apache2.conf

#LogFormat “%h %l %u %t \”%r\” %>s %b \”%{Referer}i\” \”%{User-Agent}i\”” combined
LogFormat “%v %h %l %u %t \”%r\” %>s %b \”%{Referer}i\” \”%{User-Agent}i\”” combined
Add the following CustomLog line to the same file (you can put it directly after the LogFormat line)

vi /etc/apache2/apache2.conf

CustomLog “| /usr/sbin/vlogger -s access.log /var/log/apache2? combined
NOTE
We only need one CustomLog directive in our whole Apache configuration. Please disable all other CustomLog directives, especially in your virtual host configurations.

Restart apache

# /etc/init.d/apache2 restart
Vlogger will now create subdirectories in the /var/log/apache2 directory, one per virtual host, and create access logs that contain the current date in the file name. It will also create a symlink called access.log that points to the current log file.

Let’s assume we have two virtual hosts, www.example1.com and www.example2.com. Then this is how the /var/log/apache2 directory will look like:

# ls /var/log/apache2/

www.example1.com/
09022008-access.log
09012008-access.log
access.log -> 09022008-access.log
www.example2.com/
09022008-access.log
09012008-access.log
access.log -> 09022008-access.log

SHORTENING APACHE CONFIGS USING MOD_MACRO

It is possible to use macros in the Apache config files to shorten them and make them easier to read and manage. To use this you have to install mod_macro if it’s not already installed in your distribution.

Sample mod_macro usage



ServerName $domain
ServerAlias www.$domain
DocumentRoot /vaw/www/$customer/htdocs/$domain/
ScriptAlias /cgi-bin/ /var/www/$customer/cgi-bin/
ErrorLog /var/log/apache/$customer/logs/$domain-error.log
CustomLog /var/log/apache/$customer/logs/$domain-access.log combined

Options ExecCGI,noIndexes


Use VHost customer_A example.com
Use VHost customer_B example.net
Use VHost customer_C example.org
Another example


AuthName “Restricted area”
AuthType Basic
AuthUserFile /var/www/.htpasswd
require valid-user


Options Indexes


Use PasswordProtect
Options -Indexes


Use PasswordProtect
Options +FollowSymLinks

MOD_REWRITE, A BEGINNERS GUIDE

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

You can use mod_rewrite to redirect all pages to one central PHP page, which then loads the data that the user wanted from an external data file. Lots of people use mod_rewrite to show an “alternative” image when people are hotlinking directly to their images.

Assuming the mod_rewrite module is loaded, then you’re good to go!

A simple mod_rewrite example

So, let’s write a simple mod_rewrite example. This isn’t going to be anything fancy; we’re just going to redirect people who ask for alice.html to the page bob.html instead. First, let’s create the Alice and Bob pages. Below is Alice’s webpage – create a similar one for Bob.

This is Alice’s webpage
Upload both of these to your web server, and check that you can view both of them. Now comes the fun – we’re going to add a couple of lines to your .htaccess file. The .htaccess file is a text file which contains Apache directives. Any directives which you place in it will apply to the directory which the .htaccess file sits in, and any below it. To ours, we’re going to add the following:

RewriteEngine on
RewriteRule ^alice.html$ bob.html
Upload this .htaccess file to the same directory as alice.html and bob.html, and reload Alice’s page. You should see Bob’s page being displayed, but Alice’s URL. If you still see Alice’s page being displayed, then check you’ve followed the instructions correctly (you may have to clear your cache). If things still aren’t working for you, then contact your technical support people and ask them to enable mod_rewrite and the FileInfo override in their httpd.conf file for you

The structure of a RewriteRule

RewriteRule Pattern Substitution [OptionalFlags]
The general structure of a RewriteRule is fairly simple if you already understand regular expressions. This article isn’t intended to be a tutorial about regular expressions though – there are already plenty of those available. RewriteRules are broken up as follows:

RewriteRule

This is just the name of the command.

Pattern

A regular expression which will be applied to the “current” URL. If any RewriteRules have already been performed on the requested URL, then that changed URL will be the current URL.

Substitution

Substitution occurs in the same way as it does in Perl, PHP, etc.

You can include backreferences and server variable names (%{VARNAME}) in the substitution. Backreferences to this RewriteRule should be written as $N, whereas backreferences to the previous RewriteCond should be written as %N.

A special substitution is -. This substitution tells Apache to not perform any substitution. I personally find that this is useful when using the F or G flags (see below), but there are other uses as well.

OptionalFlags

This is the only part of the RewriteRule which isn’t mandatory. Any flags which you use should be surrounded in square brackets, and comma separated. The flags which I find to be most useful are:

F – Forbidden. The user will receive a 403 error.
L – Last Rule. No more rules will be proccessed if this one was successful.
R[=code] – Redirect. The user’s web browser will be visibly redirected to the substituted URL. If you use this flag, you must prefix the substitution with http://www.somesite.com/, thus making it into a true URL. If no code is given, then a HTTP reponse of 302 (temporarily moved) is sent.
A full list of flags is given in the Apache mod_rewrite manual.

A slightly more complicated mod_rewrite example

Let’s try a slightly more meaty example now. Suppose you have a web page which takes a parameter. This parameter tells the page how to be displayed, and what content to pull into it. Humans don’t tend to like remembering the additional syntax of query strings for URLs, and neither do search engines. Both sets of people seem to much prefer a straight URL, with no extra bits tacked onto the end.

In our example, you’ve created a main index page with takes a page parameter. So, a link like index.php?page=software would take you to a software page, while a link to index.php?page=interests would take you to an interests page. What we’ll do with mod_rewrite is to silently redirect users from page/software/ to index.php?page=software etc.

The following is what needs to go into your .htaccess file to accomplish that:

RewriteEngine on
RewriteRule ^page/([^/\.]+)/?$ index.php?page=$1 [L]

Let’s walk through that RewriteRule, and work out exactly what’s going on:

^page/

Sees whether the requested page starts with page/. If it doesn’t, this rule will be ignored.

([^/.]+)

Here, the enclosing brackets signify that anything that is matched will be remembered by the RewriteRule. Inside the brackets, it says “I’d like one or more characters that aren’t a forward slash or a period, please”. Whatever is found here will be captured and remembered.

/?$

Makes sure that the only thing that is found after what was just matched is a possible forward slash, and nothing else. If anything else is found, then this RewriteRule will be ignored.

index.php?page=$1

The actual page which will be loaded by Apache. $1 is magically replaced with the text which was captured previously.

[L]

Tells Apache to not process any more RewriteRules if this one was successful.

Let’s write a quick page to test that this is working. The following test script will simply echo the name of the page you asked for to the screen, so that you can check that the RewriteRule is working.

The requested page was:
< ?php echo $_GET['page']; ?>
Again, upload both the index.php page, and the .htaccess file to the same directory. Then, test it! If you put the page in http://www.somesite.com/mime_test/, then try requesting http://www.somesite.com/mime_test/page/software. The URL in your browser window will show the name of the page which you requested, but the content of the page will be created by the index.php script! This technique can obviously be extended to pass multiple query strings to a page – all you’re limited by is your imagination.

Conditional Statements and mod_rewrite

But what happens when you start getting people hotlinking to your images (or other files)? Hot linking is the act of including an image, media file, etc from someone else’s server in one of your own pages as if it were your own. Obviously, as a webmaster, there are plenty of times when you don’t want people doing that. You’ll almost certainly have seen examples where someone has linked to one image on a website, only for a completely different, “nasty” one to be shown instead. So, how is this done?

It’s pretty simple really. All it takes are a couple of RewriteCond statements in your .htaccess file.

RewriteCond statements are as they sound – conditional statements for RewriteRules. The basic format for a RewriteCond is RewriteCond test_string cond_pattern. For our purpose, we will set the test_string to be the HTTP_REFERER. If the test string is neither empty nor our own server, then we will serve an alternative (low bandwidth) image, which tells the person who is hotlinking off for stealing our bandwidth.

Here’s how we do that:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?somesite.com/.*$ [NC]
RewriteRule \.(gif|jpg|png)$ http://www.somesite.com/nasty.gif [R,L]
Here, the RewriteRule will only be performed if all the preceeding RewriteConds are fulfilled. In the second RewriteCond, [NC] simply means “No Case”, so it doesn’t matter whether the domain name was written in upper case, lower case or a mixture of the two. So, any requests for gif, jpg or png files from referers other than somesite.com will result in your “nasty” image being shown instead.

The [R,L] in the RewriteRule simply means “Redirect, Last”. So, the RewriteRule will visibly redirect output to “nasty.gif” and no more RewriteRules will be performed on this URL.

If you simply don’t want the hot linkers to see any image at all when they hot link to your images, then simply change the final line to RewriteRule \.(gif|jpg|png)$ – [F]. The – means “don’t rewrite the requested URL”, and the [F] means “Forbidden”. So, the hot linker will get a “403 Forbidden message”, and you don’t end up wasting your bandwidth.

Conclusion

mod_rewrite is an incredibly handy tool to have in your arsenal. This article only scratched the surface of what is possible with mod_rewrite, but should have given you enough information to go out and start mod_rewriting history yourself!

BLOCKING IMAGE BANDWIDTH THEFT/HOTLINKING WITH URL REWRITING

You can stop others from hotlinking your site’s files by placing a file called .htaccess in your Apache site root (main) directory. The period before the name means the file is hidden, so you may want to edit your file as htaccess.txt, upload it to your server, then rename the txt file to .htaccess in your directory or Apache config file httpd.conf
Contact your web host on how to access your directories and configure your .htaccess file.

Example: Your site url is www.mysite.com. To stop hotlinking of your images from other sites and display a replacement image called wtf.jpg placed in your images directory, place this code in your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+.)?rmohan.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*.(jpe?g|gif|bmp|png)$ /gfx/wtf.png [L]
The first line of the above code begins the rewrite. The second line matches any requests from your own mysite.com url. The [NC] code means “No Case”, meaning match the url regardless of being in upper or lower case letters. The third line means allow empty referrals. The last line matches any files ending with the extension jpeg, jpg, gif, bmp, or png. This is then replaced by the nohotlink.jpe file in your images directory. This JPEG image is using the extension jpe instead of jpg to prevent blocking your own replacement image.

To stop hotlinking from specific outside domains only, such as myspace.com, blogspot.com and livejournal.com, but allow any other web site to hotlink images:

RewriteEngine On
RewriteCond %{HTTP_REFERER} ^http://(.+.)?myspace.com/ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://(.+.)?blogspot.com/ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://(.+.)?livejournal.com/ [NC]
RewriteRule .*.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpe [L]
You can add as many different domains as needed. Each RewriteCond line should end with the [NC,OR] code. NC means to ignore upper and lower case. OR means “Or Next”, as in, match this domain or the next line that follows. The last domain listed omits the OR code since you want to stop matching domains after the last RewriteCond line.

You can display a 403 Forbidden error code instead of an image. Replace the last line of the previous examples with this line:

RewriteRule .*.(jpe?g|gif|bmp|png)$ – [F]
Warning: Do not use .htaccess to redirect image hotlinks to another HTML page or server that isn’t your own (such as this web page). Hotlinked images can only be replaced by other images, not with an HTML page.

As with any htaccess rewrites, you may block some legitimate traffic (such as users behind proxies or firewalls) using these techniques.

Page 1 of 15912345...102030...Last »