Category Archives: Server Configuration and Handling

Advanced .htaccess security and block access using .htaccess file

Block access to files using htaccess

1. Block access to .htaccess file
Add the following code block to your htaccess file to add an extra layer of security.Any attempts to access the htaccess file will result in a 403 error message.Your first layer of security to protect htaccess files involves permissions via CHMOD to 644.

# secure your htaccess file
<Files .htaccess>
order allow,deny
deny from all
</Files>

2. Block access to a Specific File
To restrict access to a specific file, add the following code block and edit the file name, “secure_file.jpg”, with the name of the file that you wish to protect.

# prevent viewing of a specific file
<files secure_file.jpg>
order allow,deny
deny from all
</files>

3. Block access to multiple file types
To restrict access to a variety of file types, add the following code block and update the file types within parentheses to match the extensions of any files that you wish to protect.

<FilesMatch “\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$”>
Order Allow,Deny
Deny from all
</FilesMatch>

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

# disables directory browsing
Options All -Indexes

To enable directory browsing, use the following directive.

# enables directory browsing
Options All +Indexes

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

# prevent folder listing
IndexIgnore *

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

# prevent display of select file types
IndexIgnore *.wmv *.avi *.mp4 *.etc

Definition of .htaccess Regex Characters

Definition of .htaccess Regex Characters & htaccess regular expression special characters

 

#
The # instructs the server to ignore the line. It is used for including comments. Each line of comments requires its own #. When including comments, it is good practice to use only letters, numbers, dashes, and underscores. This will help eliminate/avoid potential server parsing errors.

 

[F]
Forbidden: Instructs the server to return a 403 Forbidden to the client or browser.

 

[L]
Last rule: Instructs the server to stop rewriting after the preceding directive is processed.

 

[N]
Next: Instructs Apache to rerun the rewrite rule until all rewriting directives have been achieved.

 

[G]
Gone: Instructs the server to deliver Gone (no longer exists) status message.

 

[P]
Proxy: Instructs server to handle requests by mod_proxy

 

[C]
Chain: Instructs server to chain the current rule with the previous rule.

 

[R]
Redirect: Instructs Apache to issue a redirect, causing the browser to request the rewritten/modified URL.

 

[NC]
No Case: Defines any associated argument as case-insensitive.

 

[PT]
Pass Through: Instructs mod_rewrite to pass the rewritten URL back to Apache for further processing.

 

[OR]
Or: Specifies a logical “or” that ties two expressions together such that either one proving true will cause the associated rule to be applied.

 

[NE]
No Escape: Instructs the server to parse output without escaping characters.

 

[NS]
No Sub request: Instructs the server to skip the directive if internal sub-request.

 

[QSA]
Append Query String: Directs server to add the query string to the end of the expression (URL).

 

[S=x]
Skip: Instructs the server to skip the next “x” number of rules if a match is detected.

 

[E=variable: value]
Environmental Variable: Instructs the server to set the environmental variable “variable” to “value”.

 

[T=MIME-type]
Mime Type: Declares the mime type of the target resource.

 

[]
Specifies a character class, in which any character within the brackets will be a match. e.g., [xyz] will match either an x, y, or z.

 

[]+
Character class in which any combination of items within the brackets will be a match. e.g., [xyz]+ will match any number of x’s, y’s, z’s, or any combination of these characters.

 

[^]
Specifies not within a character class. e.g., [^xyz] will match any character that is neither x, y, nor z.

 

[a-z]
A dash (-) between two characters within a character class ([]) denotes the range of characters between them. e.g., [a-zA-Z] matches all lowercase and uppercase letters from a to z.

 

a{n}
Specifies an exact number, n, of the preceding character. e.g., x{3} matches exactly three x’s.

 

a{n,}
Specifies n or more of the preceding character. e.g., x{3,} matches three or more x’s.

 

a{n,m}
Specifies a range of numbers, between n and m, of the preceding character. e.g., x{3,7} matches three, four, five, six, or seven x’s.

 

()
Used to group characters together, thereby considering them as a single unit. e.g., (perishable)?press will match press, with or without the perishable prefix.

 

^
Denotes the beginning of a regex (regex = regular expression) test string. i.e., begin argument with the proceeding character.

 

$
Denotes the end of a regex (regex = regular expression) test string. i.e., end argument with the previous character.

 

?
declares as optional the preceding character. e.g., monzas? will match monza or monzas, while mon(za)? will match either mon or monza. i.e., x? matches zero or one of x.

 

!
Declares negation. e.g., “!string” matches everything except “string”.

 

.
A dot (or period) indicates any single arbitrary character.

 


Instructs “not to” rewrite the URL, as in “…domain.com.* – [F]”.

 

+
Matches one or more of the preceding character. e.g., G+ matches one or more G’s, while “+” will match one or more characters of any kind.

 

*
Matches zero or more of the preceding character. e.g., use “.*” as a wildcard.

 

|
Declares a logical “or” operator. for example, (x|y) matches x or y.

 

\
Escapes special characters ( ^ $ ! . * | ). e.g., use “\.” to indicate/escape a literal dot.

 

\.
Indicates a literal dot (escaped).

 

/*
zero or more slashes.

 

.*
Zero or more arbitrary characters.

 

^$
Defines an empty string.

 

^.*$
The standard pattern for matching everything.

 

[^/.]
Defines one character that is neither a slash nor a dot.

 

[^/.]+
Defines any number of characters which contains neither slash nor dot.

 

http://
This is a literal statement — in this case, the literal character string, “http://”.

 

^domain.*
Defines a string that begins with the term “domain”, which then may be proceeded by any number of any characters.

 

^domain\.com$
Defines the exact string “domain.com”.

 

-d
Tests if string is an existing directory

 

-f
Tests if string is an existing file

 

-s
Tests if file in test string has a non-zero value

 

Hope the above will help you a lot, if you have any issue in htaccess rules…post your valuable comment below.

 

PHP.ini file

PHP.ini is a configuration file that is used to customize behavior of PHP at runtime.

 

This enables you to easy administration in Apache web server using configuration files. The settings in which upload directory, register global variables, display errors, log errors, max uploading size setting, maximum time to execute a script, libraries available and other configurations is written in this file.You can update it according to your needs.

 

When PHP Server starts up it looks for PHP.ini file first to load various values for settings. If you made changes in PHP.ini then you need to restart your server to check the changes be effected.

 

Where is my PHP.ini file?

 

It depends where php is installed.

The path where PHP looks for its PHP.ini file is built into PHP on compile time. To find out that path, use a PHP script/function that does a phpinfo() call.This will display a huge table of all of PHP’s configuration variables, libraries and extensions available. The path to PHP.ini can be found in the first part of that table.

 

In xampp it is available on path like
D:\xampp\php\pnp.ini

 

If you want to do some custom configurations then you can also write your own PHP.ini file. For this just copy PHP.ini file, make necessary changes in values directives according to your need rename it to PHP.ini then copy it to desired location in root of your web directory or in particular folder.But hosting should allow for running this file. The PHP runtime will take values only for settings which are specified in PHP.ini file if you are using your own, for rest of settings it will take defaults of PHP runtime. So if you are writing your own PHP.ini, keep in mind to overwrite every settings specified in web server’s PHP.ini file this can not be used as an extension of web server’s PHP.ini file.

 

Instead of creating new file, you can also update the configuration settings written in PHP.ini as well.

 

If you want some special configuration(PHP) on a single page, there are some functions available start with ini_ as follows.

 

ini_set()
ini_get_all()
ini_get()
ini_restore() etc.

 

Make password protect directories using .htaccess

The directory/folder password protection or authentication systems offered by the Apache Web Server are probably the most important use of .htaccess file.We can easily make a directory password protected (or multiple directory) of a website which require a username and password to access.Password are also encrypted using one of the best encryption methods available which ensures login credentials are kept secure.

How can I do? 3 simple steps to go.

 

Create a .htaccess file

Use an ASCII text editor (Binary will not work at all) like Notepad to create a text file with the following lines of contents

AuthName “Secured Area”
AuthType Basic
AuthUserFile /path/to/your/directory/.htpasswd
require valid-user

you can also update these setting according to your requirement

AuthName

Change “Secure Area” to any name that you like. This name will be displayed when the browser prompts for a password. If, e.g that area is to be accessible only to members of your site, you can name it “Members Only Area” etc.

AuthUserFile

 You will later create a file containing passwords named as .htpasswd. The “AuthUserFile” line tells the Apache web server where it can locate this password file(.htpasswd).Ideally, the password file should be placed outside any directory accessible by visitors to your website. For example, if the main page of your web site is physically located in “/home/your-website/public-html/”, place your .htpasswd file in /home/your-website/.htpasswd. That way, on the off-chance that your host misconfigures your server, your visitors cannot view the .htpasswd contents by simply typing http://www.your-website.com/.htpasswd.

Wherever you want to place the file, put the full path of that file after “AuthUserFile”. For example, if the directory where you placed the file is /home/your-website/.htpasswd, modify that line to “AuthUserFile /home/your-website/.htpasswd”. Note that your password file need not be named .htpasswd either. It can be any name you wish,but must started with .ht (as it is set in httpd.conf file)

AuthType and require

You do not have to modify these.Just copy the lines as it is.

 

Save and Upload the .htaccess file                                                                                                                                                                                                                                Save the .htaccess file.If you are using Notepad, be sure to save the file as “.htaccess”, including the quotes, otherwise Notepad will change the name to “.htaccess.txt”.Then upload the .htaccess file to the directory that you want to protect.

 

Set Up the Password File .htpasswd

username:encryptedpassword
scriptarticle:oCF9Pam/MXJg2

username:encryptedpassword
scriptarticle2:Tyuism/MXJ7t

 

where your-username is the login name of the user you want to give access. The user name should be a single word without any intervening spaces. You will then be prompted to enter the password for that user.

 

Place the .htpasswd file as the path given in .htaccess file.

Here is the way to get encrypted password.
click here to generate encrypted password.

or simple you make a .htpasswd using command line,if you have telnet,SSH access of the server.Here is the command.

htpasswd -c .htpasswd your-user-name

 

httpd.conf (Apache Server Configuration File)

Apache Server Configuration File

Apache has a great number of directives which you can set and manipulate in order to set your server’s behavior.

 

Every server administrator will often update some of the directives, it all depends on their particular needs. Every person working with the Apache server is likely to encounter these directives.

 

Apache HTTP Server is configured by placing directives in plain text configuration files, the main configuration file is usually called httpd.conf. The Apache HTTP Server configuration file is /etc/httpd/conf/httpd.conf. The httpd.conf file is well-commented and mostly self-explanatory.

 

Changes to the main configuration files are only taken by Apache only if started/restarted.It stores information on various functions of the server, which can be edited by removing or adding a number sign “#” at the beginning of the line, thus setting values for each directive.

 

Apache configuration files contain one directive per line. The backslash “\” may be used as the last character on a line to indicate that the directive continues onto the next line. There must be no other characters or white space between the backslash and the end of the line.

 

Directives in the configuration files are case-insensitive, but arguments of directives are  case sensitive. Lines that begin with the hash character “#” are considered comments, and are ignored.

 

Basic Paths of httpd.conf file in Unix/Linux system.

/var/www/conf/httpd.conf
/usr/local/apache/conf/httpd.conf
/etc/httpd/conf/httpd.conf

httpd.conf on windows

D:\xampp\apache\conf\httpd.conf

 

Let’s discuss some most basic directives of Apache Server:

 

ServerName

 

The ServerName directive is used to set the host name of the server, this is how the server identifies itself. It uses this name when responding to HTTP requests.

You can set this directive either in the server’s configuration or virtual hosts. The location of your configuration files depend on both the Apache version and Linux distribution.

[sourcecode language=”plain”]

<VirtualHost *:80>
ServerAdmin  [email protected]
DocumentRoot  /var/www
ServerName  www.examplesite.com
.
</VirtualHost>

[/sourcecode]

If the ServerName directive is not specified, the server tries to obtain it by performing a reverse DNS look-up on its IP address. You should always set a ServerName for the server explicitly; it is the only value you need to set to get your server running after installation.

 

You will have to use the IP address of your machine if you don’t yet have a registered domain name. Otherwise, you would need to add the domain name and IP address to the server’s hosts file- the same as you do with your PC’s hosts file. By doing this, the server checks its hosts file before consulting with the DNS server.

 

Assuming our domain name is www.examplesite.com and our server’s IP address is 117.220.48.20, you need to add the following line to the server’s hosts file (/etc/hosts):

[sourcecode language=”plain”]
117.220.48.20    www.examplesite.com    examplesite.com
[/sourcecode]

 

After editing the hosts file, you need to restart (or stop and start) Apache.

 

Listen

 

The Listen directive tells Apache what IP addresses and/or ports it should listen to for incoming requests. If nothing is specified, Apache listens to all addresses and ports on the machine. The default configuration sets the server to listen to port 80, the default port for HTTP communication.

 

If you only specify an IP address, the server will respond to requests coming to all ports of that address (also called an interface). If only a port number is specified, then Apache responds to requests on the specified port arriving at all interfaces on the machine. If an address and port combination is supplied, then Apache only responds to those specific interface/port combinations.

 

If your server installation has separate configuration files, you should be able to find or set this directive in the ports.conf file.

 

You can find this file in the same location as your Apache configuration files (mine is /etc/apache2/ports.conf, but that might be different for other Apache versions and/or Linux distributions).

 

Let’s assume our example site is at IP address 117.220.48.20. To set Apache to listen to ports 80 and 443, the respective default ports for HTTP and HTTPS, you need to enter the following directives in your ports.conf file:

[sourcecode language=”plain”]
Listen 117.220.48.20:80
Listen 117.220.48.20:443
[/sourcecode]

Alternatively, if you want Apache to listen to ports 80 and 443 on all interfaces regardless of the IP address, you can enter the following:

[sourcecode language=”plain”]
Listen 80
Listen 443
[/sourcecode]

 

Web User and Group

 

On Unix operating systems, it’s a good idea to configure Apache to run under a specific user and group instead of root. Doing so makes the server more secure and less vulnerable to attacks. Ideally, the user and group you set should not be able to login to the server (ie: have no login credentials) and no login shell; they will just be used for handling web client requests. Set the Apache user’s home directory to the web server’s document directory, usually located at /var/www or /usr/local/apache2/htdocs.

[sourcecode language=”plain”]
groupadd anyUserName
useradd -d /var/www  -g anyUserName -s /bin/false
[/sourcecode]

The example above uses anyUserName as our web user and group; just use a name not reserved for other processes. -d /var/www sets the home directory of the new account to /var/www, and -s /bin/false ensures the new account has no shell access. Next, you need to modify your config file to use the new Apache user and group. If yours says:

[sourcecode language=”plain”]
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
[/sourcecode]

Then you need to find where these variables are defined and change their values. Usually, the above directive is preceded by a comment letting you know exactly where to set the new values. Otherwise, you will just insert the new user and group name in place of the old. So your final config lines could look like this:

 

[sourcecode language=”plain”]
User anyUserName
Group anyUserName
[/sourcecode]

 

ServerRoot

 

Apache’s important files, like the server’s configuration, error, and log files are kept at the top of the directory tree. This location is the ServerRoot, and you can set a different value in Apache’s main config file. Depending on your installation, the default can be something like /usr/local/apache2 or /etc/apache2. Any Apache directives using a relative path will, by default, append to the root path specified in ServerRoot.

 

When you first install your server, the configuration and log files are placed in the ServerRoot. You can change its value to a new directory, but make sure to copy the configuration files to the new location. Also, make sure you do not to add a trailing slash to the path when you modify the value.

 

ErrorLog

 

When an error occurs, Apache logs the error to a log file. The location of the error log is determined by the value specified using the ErrorLog directive. This file is critical because you will refer to it in order to debug errors, solve server configuration problems, and optimize the server.

 

If the server hosts multiple sites and you want to have separate error logs for each site, you can specify a different file and location for each site in the virtual hosts file.

 

If you don’t, then all sites’ errors are logged in the default error log, typically located at /usr/local/apache2/logs/error_log or /var/log/apache2/error.log (once again, depending on your installation).

 

Please note that the above log paths are absolute.

 

[sourcecode language=”plain”]
ErrorLog logs/error_log
[/sourcecode]

This is a relative path. Therefore, the actual error log location is $ServerRoot/logs/error_log.

 

The LogLevel directive controls the level of the messages logged in the error logs. By default, it is set to warn, meaning that all messages with the value of warning and higher (as in more critical) will be logged. You can change the value of this directive to adjust the logging level to your preference.

 

DocumentRoot

 

The DocumentRoot directive sets the location of the server’s public files, like htdocs. This is the default Apache web server document directory, and its contents are readily and publicly available to clients connecting through the web. It contains the static and dynamic content to be served once the server receives an HTTP request for them. Since files and sub-directories under htdocs are available for the public, it is very important to handle permissions correctly in order to minimize the ability to compromise the server’s safety and security.

 

Depending on your installation, the default DocumentRoot location could be something like /var/www or /usr/local/apache2/htdocs.

 

If you are hosting multiple websites on the same server, you need to set a different DocumentRoot for each site. This can be done within the respective VirtualHost directive that corresponds to each site. Let’s say you have three websites on the same server (eg: www.examplesite1.com, www.examplesite2.com, www.examplesite3.com), your virtual hosts file might look something like the following:

 

[sourcecode language=”plain”]
<VirtualHost www.examplesite1.com>
DocumentRoot  /usr/local/apache2/htdocs/example_site1
ServerName  www.examplesite1.com
.
</VirtualHost>
[/sourcecode]

To set a separate error log for each of these domains, which is really a good idea, then your virtual hosts will like this:

[sourcecode language=”plain”]

<VirtualHost www.examplesite1.com>
DocumentRoot  /usr/local/apache2/htdocs/example_site1
ServerName  www.examplesite1.com
ErrorLog  /usr/local/apache2/logs/site1_error_log
.
</VirtualHost>

<VirtualHost www.examplesite2.com>
DocumentRoot  /usr/local/apache2/htdocs/example_site2
ServerName  www.examplesite2.com
ErrorLog  /usr/local/apache2/logs/site2_error_log
.
</VirtualHost>
[/sourcecode]

 

PidFile

 

The ServerName directive is used to set the host name of the server; this is how the server identifies itself.

 

The Apache service first starts as root in order to bind to the privileged port 80 for HTTP (or 443 if using SSL) because port numbers less than 1024 are only reserved to the root user. After the initial execution, children processes spawn to handle client requests which are owned by the Apache user specified in the configuration file. For this reason, you will find one root process and multiple processes belonging to the web user; this root process is the first one initiated when Apache starts. It has a process ID, and this ID is stored in the Pid file on the server. You can control the location of the Pid file by using the PidFile directive in the configuration file.

 

If you open the file specified in the PidFile directive, you will find a number that corresponds to the parent process ID. You can stop the Apache server by killing the process using its ID number. However, kill the process only as a last resort.

 

File Inclusion

 

It is possible to separate server configuration and settings into multiple files; in fact, some Apache installations actually do so. These multiple files can then be included in the original server config file. This approach is ideal in order to keep your config file light and clear, but it also forces you to look inside multiple files residing in different locations to completely understand how Apache is configured. In any case, below is the syntax for including external config files. Whether or not you want to use file inclusion is up to you:

 

[sourcecode language=”plain”]
# Include ports listing:
Include /etc/apache2/ports.conf

# Include generic snippets of statements
Include /etc/apache2/conf.d/

# Include module configuration:
Include /etc/apache2/mods-enabled/*.load
Include /etc/apache2/mods-enabled/*.conf
[/sourcecode]

As you can see from the examples above, you can include a specific file by name, a directory (and thus all files therein), or multiple files by using wildcards.

 

Start, Stop, and Restart Apache

 

Every time you edit one of Apache’s configuration files, you need to restart (or stop and start) the service so that Apache can load the new configuration.
Otherwise, your changes will just remain on file for the next restart or server start. If your changes cause syntax errors in the configuration files, restarting will show you error messages concerning those mistakes. Additionally, the

Apache web server will not start until you fix those errors.

 

To stop the Apache server, type in the following command in the console:

[sourcecode language=”plain”]/etc/init.d/apache2 stop[/sourcecode]

To start the Apache server, type in the following command:

[sourcecode language=”plain”]/etc/init.d/apache2 start[/sourcecode]

To restart the Apache server, type in the following command:

[sourcecode language=”plain”]/etc/init.d/apache2 restart[/sourcecode]

 

Naturally, you must be logged in with a privileged user in order to execute these commands. You could, however, still run the above commands by adding sudo before each line. This basically tells the system that you are executing the command as a super user (hence the naming, sudo), in which case the system asks you to enter a password before it executes your command. If you don’t know that password, ask your server admin. Preceding the above commands with sudo:

 

[sourcecode language=”plain”]
sudo /etc/init.d/apache2 stop
sudo /etc/init.d/apache2 start
sudo /etc/init.d/apache2 restart
[/sourcecode]

 

If you have XAMPP, then you will get a User Interface to updating these directive as well as the start and stop the Apache service on a single click.

 

In the day to day of PHP programming I am sure you usually need to update these Apache directive, in the same way These above information will be helpful to you.

 

Let me know, if you need any help related to above, I’ll be glad to help you always.

Post you comment with your suggestion or queries. Thanks!

 

Basics of .htaccess

A .htaccess (hypertext access) file is a configuration file for use on web servers running the Apache Web Server.It is a directory-level configuration file,as the name .htaccess reflects – allow per-directory access control, e.g requiring a password to access the content.

 

When a .htaccess file is placed in a directory or folder, then the .htaccess file is detected and executed by the web server it is called overridden of .htaccess.

These .htaccess files can be used to alter the configuration (global configuration for that directory, and all sub-directories if there) of the Apache Web Server to enable/disable additional functionality and features that the Apache Web Server has to offer by default.
These facilities include basic redirect functionality, for instance if a 404 file not found error occurs and others, or for more advanced functions such as content/directory password protection or image hot link prevention and content type and character set setting.

 

.htaccess files must be uploaded as ASCII mode, not BINARY and need to CHMOD the .htaccess file to 644 or (RW-R–R–). This permission makes the file usable by the server, but prevents it from being read by a browser.Suppose if you have password protected directories and browser can read the .htaccess file, then they can get the location of the authentication file and then the list to get full access to any portion that you previously had protected.

 

These are some common usage of .htaccess file

  1. Authorization, authentication
  2. Rewriting URLs
  3. Blocking
  4. SSI
  5. Directory listing
  6. Customized error responses
  7. MIME types
  8. Cache Control