Install mod_security

1. Login to your server through SSH and su to the root user.

2. First your going to start out by grabbing the latest version of mod_security
wget http://www.modsecurity.org/download/…y-1.7.4.tar.gz

3. Next we untar the archive and cd into the directory:
tar zxvf mod_security-1.7.4.tar.gz
cd mod_security-1.7.4/
Đọc tiếp »

.htaccess là gì ?

-.htaccess là một tập tin được đặt trên các máy chủ hệ Unix (FreeBSD Linux Solaris True64…) và .htaccess chỉ được cấu hình ở mức thư mục.

-Tập tin này có thể điều khiển được khá nhiều thứ thậm chí thay đổi được cả thiết lập mặc định của máy chủ Apache.

-Nếu khai thác tốt .htaccess ta có thể làm nhiều việc khá dễ dàng chỉ với vài dòng lệnh.

Lưu ý khi sử dụng tập tin .htaccess:
Đọc tiếp »

Gỡ cài đặt hoặc gỡ bỏ và Vô hiệu hoá ModSecurity

ModSecurity là một mã nguồn mở embeddable trang web ứng dụng tường lửa, hoặc đột nhập phát hiện và phòng, chống động cơ cho các ứng dụng web ModSecurity cung cấp bảo vệ khỏi một loạt các cuộc tấn công chống lại trang web cho phép các ứng dụng và giám sát lưu lượng truy cập HTTP và thời gian thực mà không có phân tích các thay đổi vào cơ sở hạ tầng hiện có, bằng cách điều hành như là một mô-đun máy chủ web Apache mod_security hoặc standalone, và do đó tăng cường bảo mật ứng dụng web. Tuy nhiên, sai hoặc đặt ra những quy định quá nghiêm ngặt, ModSecurity có thể gây ra các trang web của bạn để trở về các lỗi như: HTTP 403 Forbidden lỗi hoặc truy cập bị từ chối lỗi, vấn đề về đăng nhập, hoặc HTTP 412 Precondition Không lỗi, hoặc HTTP 406 Không thể chấp nhận lỗi sai và các triệu chứng tích cực .
Đọc tiếp »

Remove and Uninstall or Disable ModSecurity (Tieng Anh)

ModSecurity is an open source embeddable web application firewall, or intrusion detection and prevention engine for web applications. ModSecurity provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring and real-time analysis with no changes to existing infrastructure, by operating as an Apache Web server module mod_security or standalone, and thus increase web application security. However, misconfigured or overly strict rule sets, ModSecurity may cause your website to return various errors such as HTTP 403 Forbidden error or access denied error, login problems, or HTTP 412 Precondition Failed error, or HTTP 406 Not Acceptable error and other false positive symptoms.
Đọc tiếp »

10 biện pháp bảo mật Apache

 1 . Cập nhật liên tục

Việc Apache chạy trên hệ điều hành Linux không có nghĩa là bạn không cần cập nhật. Những lỗ hổng mới và những nguy cơ bảo mật luôn thường trực. Bạn nên thường xuyên cập nhật để vá những lỗ hổng và sửa những lỗi bảo mật đó. Nếu đã cài đặt Apache cùng với trình quản lý gói của bản phân phối, bạn có thể thực hiện cập nhật rất dễ dàng. Và nếu cài đặt từ nguồn, cần đảm bảo rằng quá trình cập nhật sẽ không làm thay đổi module hay những thành phần phụ của website. Ngoài ra nếu sử dụng PHP thì trong quá trình cập nhật Apache bạn phải đồng thời cập nhật cả hai.
Đọc tiếp »

Tắt Mod_security trên một site nào đó

Tìm đến file cấu hình của Apache httpd.conf và mở nó ra

Tìm đến vị trí host nào đó trong thẻ <VirtualHost> thêm đoạn code sau vào để tắt chế độ Mod_security cho vị trí host đó.

<IfModule mod_security2.c>
SecRuleEngine Off
</IfModule>

Lưu lại file httpd.conf và khởi động lại Apache là ok.

Apache và Mod_rewrite

Mod_rewrite cho phép bạn viết lại webpage’s url. Và bạn có thể viết lại URL cho hầu như  nhiều thứ.

Mặc định Apache đã tích hợp Mod_rewrite nhưng muốn sử  dụng nó thì phải enable lên.

1.Enable

Tìm tập tin cấu hình của Apache có tên là httpd.conf.Mở nó ra và tìm đến dòng LoadModule rewrite_module modules/mod_rewrite.so

Bỏ dấu ; trước dòng này và chắc chắn hai dòng này đều bỏ dấu ; trước nó
Đọc tiếp »

Tomcat 5.5.17, with mod_jk Building a Web Server, for Windows

Requirements

  • Java 1.5 JDK (SDK)
  • Apache 2.0
  • mod_jk 1.2

Download

Đọc tiếp »

Setting up LAMPP using XAMPP

Here goes my first Linux Tutorial for LAMPP using XAMPP. Actually i was searching for a way to install LAMP on my debian system when i came across this wonderful tutorial. Thought would be nice to share it.

Step 1: Download
http://www.apachefriends.org/en/xampp-linux.html

Step 2: Installation

Đọc tiếp »

Cài LAMPP cho Ubuntu

Bạn là lập trình viên PHP chuyên nghiệp, hãy cài đặt ngay XAMPP cho Ubuntu để làm việc thôi.

Lưu ý: Tôi chỉ cách cài XAMPP (Apache + PHP + MySQL + PhpMyAdmin), còn bạn nào thích cài riêng từng thứ vẫn được.

Tiến hành theo trình tự sau:

* Bước 1: Download gói XAMPP về. Phiên bản mới nhất là XAMPP 1.6.6. Download here
* Bước 2: Tiến hành cài đặt. Gõ lệnh: sudo tar xvfz xampp-linux-1.6.6.tar.gz -C /opt

* Bước 3: Khởi động XAMPP. Gõ lệnh sudo /opt/lampp/lampp start
* Bước 4: Test thử 01 chương trình. Giả sử bạn đã có file test.php với nội dung như sau:

Mã:
<? phpinfo(); ?>

Mở trình duyệt ra (sẵn có theo Ubuntu 8.04 là FireFox 3 Bêta 5) gõ vào http://localhost/test.php
Để tạo file test.php, đơn giản nhất bạn tìm đến thư mục LAMPP nằm trong /opt, tìm đến thư mục htdocs và tạo nó.
Có thể bạn không tạo được, hãy mở Terminal và gõ sudo nautilus và thao tác y hệt Windows.

* Bước 5: Thoát XAMPP. Gõ lệnh: sudo /opt/lampp/lampp stop

An toàn hơn với Webserver Apache

Cùng với việc ra đời của các Website trên mạng cũng đồng thời xuất hiện các cuộc tấn công khai thác các lỗ hổng của máy chủ Web ngày một nhiều. Tuy nhiên, phần lớn các lỗ hổng kể trên được tạo ra do sơ xuất hoặc cấu hình sai của người quản trị. Bài viết sau đây giới thiệu một số kỹ năng căn bản về an toàn với Webserver Apache – một trong những Webserver phổ biến nhất trên Internet.

Giới hạn địa chỉ ip

Đọc tiếp »

Configuration Directives in httpd.conf

10.5.1. General Configuration Tips

If configuring the Apache HTTP Server, edit /etc/httpd/conf/httpd.conf and then either reload, restart, or stop and start the httpdSection 10.4 Starting and Stopping httpd. process as outlined in

Before editing httpd.conf, make a copy the original file. Creating a backup makes it easier to recover from mistakes made while editing the configuration file.

If a mistake is made and the Web server does not work correctly, first review recently edited passages in httpd.conf to verify there are no typos.

Next look in the Web server’s error log, /var/log/httpd/error_log. The error log may not be easy to interpret, depending on your level of expertise. However, the last entries in the error log should provide useful information.

The following subsections contain a list of short descriptions for many of the directives included in httpd.conf. These descriptions are not exhaustive. For more information, refer to the Apache documentation online at http://httpd.apache.org/docs-2.0/.

For more information about mod_ssl directives, refer to the documentation online at http://httpd.apache.org/docs-2.0/mod/mod_ssl.html.

10.5.2. ServerRoot

The ServerRoot directive specifies the top-level directory containing website content. By default, ServerRoot is set to "/etc/httpd" for both secure and non-secure servers.

10.5.3. PidFile

PidFile names the file where the server records its process ID (PID). By default the PID is listed in /var/run/httpd.pid.

10.5.4. Timeout

Timeout defines, in seconds, the amount of time that the server waits for receipts and transmissions during communications. Timeout is set to 300 seconds by default, which is appropriate for most situations.

10.5.5. KeepAlive

KeepAlive sets whether the server allows more than one request per connection and can be used to prevent any one client from consuming too much of the server’s resources.

By default Keepalive is set to off. If Keepalive is set to on and the server becomes very busy, the server can quickly spawn the maximum number of child processes. In this situation, the server slows down significantly. If Keepalive is enabled, it is a good idea to set the the KeepAliveTimeout low (refer to Section 10.5.7 KeepAliveTimeout for more information about the KeepAliveTimeout directive) and monitor the /var/log/httpd/error_log log file on the server. This log reports when the server is running out of child processes.

10.5.6. MaxKeepAliveRequests

This directive sets the maximum number of requests allowed per persistent connection. The Apache Project recommends a high setting, which improves the server’s performance. MaxKeepAliveRequests is set to 100 by default, which should be appropriate for most situations.

10.5.7. KeepAliveTimeout

KeepAliveTimeout sets the number of seconds the server waits after a request has been served before it closes the connection. Once the server receives a request, the Timeout directive applies instead. KeepAliveTimeout is set to 15 seconds by default.

10.5.8. IfModule

<IfModule> and </IfModule> tags create a conditional container which are only activated if the specified module is loaded. Directives within the IfModule container are processed under one of two conditions. The directives are processed if the module contained within the starting <IfModule> tag is loaded. Or, if an exclamation point [!] appears before the module name, the directives are processed only if the module specified in the <IfModule> tag is not loaded.

For more information about Apache HTTP Server modules, refer to Section 10.7 Adding Modules.

10.5.9. MPM Specific Server-Pool Directives

As explained in Section 10.2.1.2 Server-Pool Size Regulation, under Apache HTTP Server 2.0 the responsibility for managing characteristics of the server-pool falls to a module group called MPMs. The characteristics of the server-pool differ depending upon which MPM is used. For this reason, an IfModule container is necessary to define the server-pool for the MPM in use.

By default, Apache HTTP Server 2.0 defines the server-pool for both the prefork and worker MPMs.

The following a list of directives found within the MPM-specific server-pool containers.

10.5.9.1. StartServers

StartServers sets how many server processes are created upon startup. Since the Web server dynamically kills and creates server processes based on traffic load, it is not necessary to change this parameter. The Web server is set to start 8 server processes at startup for the prefork MPM and 2 for the worker MPM.

10.5.9.2. MaxRequestsPerChild

MaxRequestsPerChild sets the total number of requests each child server process serves before the child dies. The main reason for setting MaxRequestsPerChild is to avoid long-lived process induced memory leaks. The default MaxRequestsPerChild for the prefork MPM is 1000 and for the worker MPM is 0.

10.5.9.3. MaxClients

MaxClients sets a limit on the total number of server processes, or simultaneously connected clients, that can run at one time. The main purpose of this directive is to keep a runaway Apache HTTP Server from crashing the operating system. For busy servers this value should be set to a high value. The server’s default is set to 150 regardless of the MPM in use. However, it is not recommended that the value for MaxClients exceeds 256 when using the prefork MPM.

10.5.9.4. MinSpareServers and MaxSpareServers

These values are only used with the prefork MPM. They adjust how the Apache HTTP Server dynamically adapts to the perceived load by maintaining an appropriate number of spare server processes based on the number of incoming requests. The server checks the number of servers waiting for a request and kills some if there are more than MaxSpareServers or creates some if the number of servers is less than MinSpareServers.

The default MinSpareServers value is 5; the default MaxSpareServers value is 20. These default settings should be appropriate for most situations. Be careful not to increase the MinSpareServers to a large number as doing so creates a heavy processing load on the server even when traffic is light.

10.5.9.5. MinSpareThreads and MaxSpareThreads

These values are only used with the worker MPM. They adjust how the Apache HTTP Server dynamically adapts to the perceived load by maintaining an appropriate number of spare server threads based on the number of incoming requests. The server checks the number of server threads waiting for a request and kills some if there are more than MaxSpareThreads or creates some if the number of servers is less than MinSpareThreads.

The default MinSpareThreads value is 25; the default MaxSpareThreads value is 75. These default settings should be appropriate for most situations. The value for MaxSpareThreads is must be greater than or equal to the sum of MinSpareThreads and ThreadsPerChild or Apache HTTP Server automatically corrects it.

10.5.9.6. ThreadsPerChild

This value is only used with the worker MPM. It sets the number of threads within each child process. The default value for this directive is 25.

10.5.10. Listen

The Listen command identifies the ports on which the Web server accepts incoming requests. By default, the Apache HTTP Server is set to listen to port 80 for non-secure Web communications and (in the /etc/httpd/conf.d/ssl.conf file which defines any secure servers) to port 443 for secure Web communications.

If the Apache HTTP Server is configured to listen to a port under 1024, only the root user can start it. For port 1024 and above, httpd can be started as a regular user.

The Listen directive can also be used to specify particular IP addresses over which the server accepts connections.

10.5.11. Include

Include allows other configuration files to be included at runtime.

The path to these configuration files can be absolute or relative to the ServerRoot.

Important Important
  For the server to use individually packaged modules, such as mod_ssl, mod_perl, and php, the following directive must be included in Section 1: Global Environment of httpd.conf:

Include conf.d/*.conf

10.5.12. LoadModule

LoadModule is used to load in Dynamic Shared Object (DSO) modules. More information on the Apache HTTP Server’s DSO support, including instructions for using the LoadModule directive, can be found in Section 10.7 Adding Modules. Note, the load order of the modules is no longer important with Apache HTTP Server 2.0. Refer to Section 10.2.1.3 Dynamic Shared Object (DSO) Support for more information about Apache HTTP Server 2.0 DSO support.

10.5.13. ExtendedStatus

The ExtendedStatus directive controls whether Apache generates basic (off) or detailed server status information (on), when the server-status handler is called. The Server-status handler is called using Location tags. More information on calling server-status is included in Section 10.5.59 Location.

10.5.14. IfDefine

The IfDefine tags surround configuration directives that are applied if the “test” stated in the IfDefine tag is true. The directives are ignored if the test is false.

The test in the IfDefine tags is a parameter name (for example, HAVE_PERL). If the parameter is defined, meaning that it is provided as an argument to the server’s start-up command, then the test is true. In this case, when the Web server is started, the test is true and the directives contained in the IfDefine tags are applied.

10.5.15. User

The User directive sets the user name of the server process and determines what files the server is allowed to access. Any files inaccessible to this user are also inaccessible to clients connecting to the Apache HTTP Server.

By default User is set to apache.

Note Note
  For security reasons, the Apache HTTP Server refuses to run as the root user.

10.5.16. Group

Specifies the group name of the Apache HTTP Server processes.

By default Group is set to apache.

10.5.17. ServerAdmin

Sets the ServerAdmin directive to the email address of the Web server administrator. This email address shows up in error messages on server-generated Web pages, so users can report a problem by sending email to the server administrator.

By default, ServerAdmin is set to root@localhost.

A common way to set up ServerAdmin is to set it to webmaster@example.com. Then alias webmaster to the person responsible for the Web server in /etc/aliases and run /usr/bin/newaliases.

10.5.18. ServerName

ServerName specifies a hostname and port number (matching the Listen directive) for the server. The ServerName does not need to match the machine’s actual hostname. For example, the Web server may be www.example.com, but the server’s hostname is actually foo.example.com. The value specified in ServerName must be a valid Domain Name Service (DNS) name that can be resolved by the system — do not make something up.

The following is a sample ServerName directive:

ServerName www.example.com:80

When specifying a ServerName, be sure the IP address and server name pair are included in the /etc/hosts file.

10.5.19. UseCanonicalName

When set to on, this directive configures the Apache HTTP Server to reference itself using the value specified in the ServerName and PortUseCanonicalName is set to off, the server instead uses the value used by the requesting client when referring to itself. directives. When

UseCanonicalName is set to off by default.

10.5.20. DocumentRoot

The DocumentRoot is the directory which contains most of the HTML files which are served in response to requests. The default DocumentRoot for both the non-secure and secure Web servers is the /var/www/html directory. For example, the server might receive a request for the following document:

http://example.com/foo.html

The server looks for the following file in the default directory:

/var/www/html/foo.html

To change the DocumentRoot so that it is not shared by the secure and the non-secure Web servers, refer to Section 10.8 Virtual Hosts.

10.5.21. Directory

<Directory /path/to/directory> and </Directory> tags create a container used to enclose a group of configuration directives which apply only to a specific directory and its subdirectories. Any directive which is applicable to a directory may be used within Directory tags.

By default, very restrictive parameters are applied to the root directory (/), using the Options (refer to Section 10.5.22 Options) and AllowOverride (refer to Section 10.5.23 AllowOverride) directives. Under this configuration, any directory on the system which needs more permissive settings has to be explicitly given those settings.

In the default configuration, another Directory container is configured for the DocumentRoot which assigns less rigid parameters to the directory tree so that the Apache HTTP Server can access the files residing there.

The Directory container can be also be used to configure additional cgi-bin directories for server-side applications outside of the directory specified in the ScriptAlias directive (refer to Section 10.5.40 ScriptAlias for more information about the ScriptAlias directive).

To accomplish this, the Directory container must set the ExecCGI option for that directory.

For example, if CGI scripts are located in /home/my_cgi_directory, add the following Directory container to the httpd.conf file:

<Directory /home/my_cgi_directory>
    Options +ExecCGI
</Directory>

Next, the AddHandler directive must be uncommented to identify files with the .cgi extension as CGI scripts. Refer to Section 10.5.55 AddHandler for instructions on setting AddHandler.

For this to work, permissions for CGI scripts, and the entire path to the scripts, must be set to 0755.

10.5.22. Options

The Options directive controls which server features are available in a particular directory. For example, under the restrictive parameters specified for the root directory, Options is set to only FollowSymLinks. No features are enabled, except that the server is allowed to follow symbolic links in the root directory.

By default, in the DocumentRoot directory, Options is set to include Indexes and FollowSymLinks. Indexes permits the server to generate a directory listing for a directory if no DirectoryIndex (for example, index.html) is specified. FollowSymLinks allows the server to follow symbolic links in that directory.

Note Note
  Options statements from the main server configuration section needs to be replicated to each VirtualHost containers individually. Refer to Section 10.5.65 VirtualHost for more information about VirtualHost containers.

10.5.23. AllowOverride

The AllowOverride directive sets whether any Options can be overridden by the declarations in an .htaccess file. By default, both the root directory and the DocumentRoot are set to allow no .htaccess overrides.

10.5.24. Order

The Order directive controls the order in which allow and deny directives are evaluated. The server is configured to evaluate the AllowDeny directives for the DocumentRoot directory. directives before the

10.5.25. Allow

Allow specifies which client can access a given directory. The client can be all, a domain name, an IP address, a partial IP address, a network/netmask pair, and so on. The DocumentRoot directory is configured to Allow requests from all, meaning everyone has access.

10.5.26. Deny

Deny works similar to Allow, except it specifies who is denied access. The DocumentRoot is not configured to Deny requests from anyone by default.

10.5.27. UserDir

UserDir is the subdirectory within each user’s home directory where they should place personal HTML files which are served by the Web server. This directive is set to disable by default.

The name for the subdirectory is set to public_html in the default configuration. For example, the server might receive the following request:

http://example.com/~username/foo.html

The server would look for the file:

/home/username/public_html/foo.html

In the above example, /home/username/ is the user’s home directory (note that the default path to users’ home directories may vary).

Make sure that the permissions on the users’ home directories are set correctly. Users’ home directories must be set to 0711. The read (r) and execute (x) bits must be set on the users’ public_html directories (0755 also works). Files that are served in a users’ public_html directories must be set to at least 0644.

10.5.28. DirectoryIndex

The DirectoryIndex is the default page served by the server when a user requests an index of a directory by specifying a forward slash (/) at the end of the directory name.

When a user requests the page http://example/this_directory/, they get either the DirectoryIndex page if it exists or a server-generated directory list. The default for DirectoryIndex is index.html and the index.html.var type map. The server tries to find either of these files and returns the first one it finds. If it does not find one of these files and Options Indexes is set for that directory, the server generates and returns a listing, in HTML format, of the subdirectories and files within the directory, unless the directory listing feature is turned off.

10.5.29. AccessFileName

AccessFileName names the file which the server should use for access control information in each directory. The default is .htaccess.

Immediately after the AccessFileName directive, a set of Files tags apply access control to any file beginning with a .ht. These directives deny Web access to any .htaccess files (or other files which begin with .ht) for security reasons.

10.5.30. CacheNegotiatedDocs

By default, the Web server asks proxy servers not to cache any documents which were negotiated on the basis of content (that is, they may change over time or because of the input from the requester). If CacheNegotiatedDocs is set to on, this function is disabled and proxy servers are allowed to such cache documents.

10.5.31. TypesConfig

TypesConfig names the file which sets the default list of MIME type mappings (file name extensions to content types). The default TypesConfig file is /etc/mime.types. Instead of editing /etc/mime.types, the recommended way to add MIME type mappings is to use the AddType directive.

For more information about AddType, refer to Section 10.5.54 AddType.

10.5.32. DefaultType

DefaultType sets a default content type for the Web server to use for documents whose MIME types cannot be determined. The default is text/plain.

10.5.33. HostnameLookups

HostnameLookups can be set to on, off or double. If HostnameLookups is set to on, the server automatically resolves the IP address for each connection. Resolving the IP address means that the server makes one or more connections to a DNS server, adding processing overhead. If HostnameLookups is set to double, the server performs a double-reverse DNS look up adding even more processing overhead.

To conserve resources on the server, HostnameLookups is set to off by default.

If hostnames are required in server log files, consider running one of the many log analyzer tools that perform the DNS lookups more efficiently and in bulk when rotating the Web server log files.

10.5.34. ErrorLog

ErrorLog specifies the file where server errors are logged. By default, this directive is set to /var/log/httpd/error_log.

10.5.35. LogLevel

LogLevel sets how verbose the error messages in the error logs are. LogLevel can be set (from least verbose to most verbose) to emerg, alert, crit, error, warn, notice, info or debug. The default LogLevel is warn.

10.5.36. LogFormat

The LogFormat directive configures the format of the various Web server log files. The actual LogFormat used depends on the settings given in the CustomLog directive (refer to Section 10.5.37 CustomLog).

The following are the format options if the CustomLog directive is set to combined:

%h (remote host’s IP address or hostname)
Lists the remote IP address of the requesting client. If HostnameLookups is set to on, the client hostname is recorded unless it is not available from DNS.

%l (rfc931)
Not used. A hyphen [-] appears in the log file for this field.

%u (authenticated user)
If authentication was required, lists the user name of the user is recorded. Usually, this is not used, so a hyphen [-] appears in the log file for this field.

%t (date)
Lists the date and time of the request.

%r (request string)
Lists the request string exactly as it came from the browser or client.

%s (status)
Lists the HTTP status code which was returned to the client host.

%b (bytes)
Lists the size of the document.

%\"%{Referer}i\" (referrer)
Lists the URL of the webpage which referred the client host to Web server.

%\"%{User-Agent}i\" (user-agent)
Lists the type of Web browser making the request.

10.5.37. CustomLog

CustomLog identifies the log file and the log file format. By default, the log is recorded to the /var/log/httpd/access_log file.

The default CustomLog format is combined. The following illustrates the combined log file format:

remotehost rfc931 user date "request" status bytes referrer user-agent

10.5.38. ServerSignature

The ServerSignature directive adds a line containing the Apache HTTP Server server version and the ServerName to any server-generated documents, such as error messages sent back to clients. ServerSignature is set to on by default.

It can also be set to off or to EMail. EMail, adds a mailto:ServerAdmin HTML tag to the signature line of auto-generated responses.

10.5.39. Alias

The Alias setting allows directories outside the DocumentRoot directory to be accessible. Any URL ending in the alias automatically resolves to the alias’ path. By default, one alias for an icons/ directory is already set up. An icons/ directory can be accessed by the Web server, but the directory is not in the DocumentRoot.

10.5.40. ScriptAlias

The ScriptAlias directive defines where CGI scripts are located. Generally, it is not good practice to leave CGI scripts within the DocumentRoot, where they can potentially be viewed as text documents. For this reason, a special directory outside of the DocumentRootScriptAlias directive. This directory is known as a cgi-bin/var/www/cgi-bin/ by default. directory containing server-side executables and scripts is designated by the and set to

It is possible to establish directories for storing executables outside of the cgi-bin directory. For instructions on doing so, refer to Section 10.5.55 AddHandler and Section 10.5.21 Directory.

10.5.41. Redirect

When a webpage is moved, Redirect can be used to map the file location to a new URL. The format is as follows:

Redirect /<old-path>/<file-name> http://<current-domain>/<current-path>/<file-name>

In this example, replace <old-path> with the old path information for <file-name> and <current-domain> and <current-path> with the current domain and path information for <file-name>.

In this example, any requests for <file-name> at the old location is automatically redirected to the new location.

For more advanced redirection techniques, use the mod_rewrite module included with the Apache HTTP Server. For more information about configuring the mod_rewrite module, refer to the Apache Software Foundation documentation online at http://httpd.apache.org/docs-2.0/mod/mod_rewrite.html.

10.5.42. IndexOptions

IndexOptions controls the appearance of server generated directing listings, by adding icons, file descriptions, and so on. If Options Indexes is set (refer to Section 10.5.22 Options), the Web server generates a directory listing when the Web server receives an HTTP request for a directory without an index.

First, the Web server looks in the requested directory for a file matching the names listed in the DirectoryIndex directive (usually, index.html). If an index.html file is not found, Apache HTTP Server creates an HTML directory listing of the requested directory. The appearance of this directory listing is controlled, in part, by the IndexOptions directive.

The default configuration turns on FancyIndexing. This means that a user can re-sort a directory listing by clicking on column headers. Another click on the same header switches from ascending to descending order. FancyIndexing also shows different icons for different files, based upon file extensions.

The AddDescription option, when used in conjunction with FancyIndexing, presents a short description for the file in server generated directory listings.

IndexOptions has a number of other parameters which can be set to control the appearance of server generated directories. Parameters include IconHeight and IconWidth, to make the server include HTML HEIGHT and WIDTH tags for the icons in server generated webpages; IconsAreLinks, for making the icons act as part of the HTML link anchor along with the filename and others.

10.5.43. AddIconByEncoding

This directive names icons which are displayed by files with MIME encoding in server generated directory listings. For example, by default, the Web server shows the compressed.gif icon next to MIME encoded x-compress and x-gzip files in server generated directory listings.

10.5.44. AddIconByType

This directive names icons which are displayed next to files with MIME types in server generated directory listings. For example, the server shows the icon text.gif next to files with a mime-type of text, in server generated directory listings.

10.5.45. AddIcon

AddIcon specifies which icon to show in server generated directory listings for files with certain extensions. For example, the Web server is set to show the icon binary.gif for files with .bin or .exe extensions.

10.5.46. DefaultIcon

DefaultIcon specifies the icon displayed in server generated directory listings for files which have no other icon specified. The unknown.gif image file is the default.

10.5.47. AddDescription

When using FancyIndexing as an IndexOptions parameter, the AddDescription directive can be used to display user-specified descriptions for certain files or file types in a server generated directory listing. The AddDescription directive supports listing specific files, wildcard expressions, or file extensions.

10.5.48. ReadmeName

ReadmeName names the file which, if it exists in the directory, is appended to the end of server generated directory listings. The Web server first tries to include the file as an HTML document and then try to include it as plain text. By default, ReadmeName is set to README.html.

10.5.49. HeaderName

HeaderName names the file which, if it exists in the directory, is prepended to the start of server generated directory listings. Like ReadmeName, the server tries to include it as an HTML document if possible or in plain text if not.

10.5.50. IndexIgnore

IndexIgnore lists file extensions, partial file names, wildcard expressions or full filenames. The Web server does not include any files which match any of those parameters in server generated directory listings.

10.5.51. AddEncoding

AddEncoding names filename extensions which should specify a particular encoding type. AddEncoding can also be used to instruct some browsers to uncompress certain files as they are downloaded.

10.5.52. AddLanguage

AddLanguage associates file name extensions with specific languages. This directive is useful for Apache HTTP Servers which serve content in multiple languages based on the client Web browser’s language settings.

10.5.53. LanguagePriority

LanguagePriority sets precedence for different languages in case the client Web browser has no language preference set.

10.5.54. AddType

Use the AddType directive to define or override a default MIME type and file extension pairs. The following example directive tells the Apache HTTP Server to recognize the .tgz file extension:

AddType application/x-tar .tgz

10.5.55. AddHandler

AddHandler maps file extensions to specific handlers. For example, the cgi-script handler can be matched with the extension .cgi to automatically treat a file ending with .cgi as a CGI script. The following is a sample AddHandler directive for the .cgi extension.

AddHandler cgi-script .cgi

This directive enables CGIs outside of the cgi-bin to function in any directory on the server which has the ExecCGI option within the directories container. Refer to Section 10.5.21 Directory for more information about setting the ExecCGI option for a directory.

In addition to CGI scripts, the AddHandler directive is used to process server-parsed HTML and image-map files.

10.5.56. Action

Action specifies a MIME content type and CGI script pair, so that whenever a file of that media type is requested, a particular CGI script is executed.

10.5.57. ErrorDocument

The ErrorDocument directive associates an HTTP response code with a message or a URL to be sent back to the client. By default, the Web server outputs a simple and usually cryptic error message when an error occurs. The ErrorDocument directive forces the Web server to instead output a customized message or page.

Important Important
  To be valid, the message must be enclosed in a pair of double quotes ["].

10.5.58. BrowserMatch

The BrowserMatch directive allows the server to define environment variables and take appropriate actions based on the User-Agent HTTP header field — which identifies the client’s Web browser type. By default, the Web server uses BrowserMatch to deny connections to specific browsers with known problems and also to disable keepalives and HTTP header flushes for browsers that are known to have problems with those actions.

10.5.59. Location

The <Location> and </Location> tags create a container in which access control based on URL can be specified.

For instance, to allow people connecting from within the server’s domain to see status reports, use the following directives:

<Location /server-status>
    SetHandler server-status
    Order deny,allow
    Deny from all
    Allow from <.example.com>
</Location>

Replace <.example.com> with the second-level domain name for the Web server.

To provide server configuration reports (including installed modules and configuration directives) to requests from inside the domain, use the following directives:

<Location /server-info>
    SetHandler server-info
    Order deny,allow
    Deny from all
    Allow from <.example.com>
</Location>

Again, replace <.example.com> with the second-level domain name for the Web server.

10.5.60. ProxyRequests

To configure the Apache HTTP Server to function as a proxy server, remove the hash mark (#) from the beginning of the <IfModule mod_proxy.c> line, the ProxyRequests, and each line in the <Proxy> stanza. Set the ProxyRequests directive to On, and set which domains are allowed access to the server in the Allow from directive of the <Proxy> stanza.

10.5.61. Proxy

<Proxy *> and </Proxy> tags create a container which encloses a group of configuration directives meant to apply only to the proxy server. Many directives which are allowed within a <Directory> container may also be used within <Proxy> container.

10.5.62. ProxyVia

The ProxyVia command controls whether or not an HTTP Via: header line is sent along with requests or replies which go through the Apache proxy server. The Via: header shows the hostname if ProxyVia is set to On, shows the hostname and the Apache HTTP Server version for Full, passes along any Via: lines unchanged for Off, and Via: lines are removed for Block.

10.5.63. Cache Directives

A number of commented cache directives are supplied by the default Apache HTTP Server configuration file. In most cases, uncommenting these lines by removing the hash mark (#) from the beginning of the line is sufficient. The following, however, is a list of some of the more important cache-related directives.

  • CacheEnable — Specifies whether the cache is a disk, memory, or file descriptor cache. By default CacheEnable configures a disk cache for URLs at or below /.
  • CacheRoot — Specifies the name of the directory containing cached files. The default CacheRoot is the /var/httpd/proxy/ directory.
  • CacheSize — Specifies how much space the cache can use in kilobytes. The default CacheSize is 5 KB.

The following is a list of some of the other common cache-related directives.

  • CacheMaxExpire — Specifies how long HTML documents are retained (without a reload from the originating Web server) in the cache. The default is 24 hours (86400 seconds).
  • CacheLastModifiedFactor — Specifies the creation of an expiry (expiration) date for a document which did not come from its originating server with its own expiry set. The default CacheLastModifiedFactor is set to 0.1, meaning that the expiry date for such documents equals one-tenth of the amount of time since the document was last modified.
  • CacheDefaultExpire — Specifies the expiry time in hours for a document that was received using a protocol that does not support expiry times. The default is set to 1 hour (3600 seconds).
  • NoProxy — Specifies a space-separated list of subnets, IP addresses, domains, or hosts whose content is not cached. This setting is most useful for Intranet sites.

10.5.64. NameVirtualHost

The NameVirtualHost directive associates an IP address and port number, if necessary, for any name-based virtual hosts. Name-based virtual hosting allows one Apache HTTP Server to serve different domains without using multiple IP addresses.

Note Note
  Name-based virtual hosts only work with non-secure HTTP connections. If using virtual hosts with a secure server, use IP address-based virtual hosts instead.

To enable name-based virtual hosting, uncomment the NameVirtualHost configuration directive and add the correct IP address. Then add more VirtualHost containers for each virtual host.

10.5.65. VirtualHost

<VirtualHost> and </VirtualHost> tags create a container outlining the characteristics of a virtual host. The VirtualHost container accepts most configuration directives.

A commented VirtualHost container is provided in httpd.conf, which illustrates the minimum set of configuration directives necessary for each virtual host. Refer to Section 10.8 Virtual Hosts for more information about virtual hosts.

Installing Apache 2

Here is an example to configure Apache. I set it that users can open to the public their Web site and can execute CGI in any directories.[root@www ~]#

vi /etc/httpd/conf/httpd.conf

ServerTokens

Prod

// line 44: change

KeepAlive

On

// line 74: change to ON

ServerAdmin

root@server-linux.info

// line 250: Admin’s address

ServerName

www.server-linux.info:80

// line 264: server’s name

Options FollowSymLinks

ExecCGI

// line 319: change (disable Indexes)

AllowOverride

All

// line 326: change

#

UserDir disable

// line 354: make it comment

UserDir public_html

// line 361: make valid

// line 369 – 380 : remove # and make valid


<Directory /home/*/public_html>
AllowOverride

All

// change


Options

ExecCGI

// CGI enabled


<Limit GET POST OPTIONS>
Order allow,deny
Allow from all
</Limit>
<LimitExcept GET POST OPTIONS>
Order deny,allow
Deny from all
</LimitExcept>
</Directory>

// line 390: add file name that it can access only with directory’s name


DirectoryIndex index.html

index.cgi index.php

ServerSignature

Off

// line 523: change

#

AddDefaultCharset UTF-8

// line 746: make it comment

// line 777: make valid and add file-type that apache looks them CGI


AddHandler cgi-script .cgi

.pl

[root@www ~]#

/etc/rc.d/init.d/httpd start


Starting httpd:

[ OK ]


[root@www ~]#

chkconfig httpd on

[2] Make HTML test page and Make sure apache is working. It’s OK if following page is shown.

[root@www ~]#

cd /var/www/html


[root@www html]#

vi index.html

<html>
<body>
<div style=”width:100%;font-size:40px;font-weight:bold;text-align:center”>
Test Page
</div>
</body>
</html>

 
[3] Make CGI test page and Make sure apache is working. It’s OK if following page is shown.

[root@www ~]#

cd /var/www/html


[root@www html]#

vi index.cgi

#!/usr/local/bin/perl
print “Content-type: text/html\n\n”;
print <<”EOM”;
<html>
<body>
<div style=”width:100%;font-size:40px;font-weight:bold;text-align:center”>
CGI Test Page
</div>
</body>
</html>
EOM
exit;

[root@www ~]#

chmod 705 index.cgi


 
[4] Make PHP test page and Make sure apache is working. It’s OK if following page is shown.

[root@www ~]#

cd /var/www/html


[root@www html]#

vi index.php

<html>
<body>
<div style=”width:100%;font-size:40px;font-weight:bold;text-align:center”>
<?php

print Date(“Y/m/d”);


?>
</div>
</body>
</html>

 

Installing Apache 1

This is an example to build Web Server. Install Apache for it. In addition to do it, Install PHP and SSL because there are often used with Web Server. And it’s also neccessary to configure router so that TCP and UDP packets to 80 and 443 can pass through 

[root@www ~]#

yum -y install httpd php php-mbstring php-pear mod_ssl


Loading “installonlyn” plugin
Loading “fastestmirror” plugin
Setting up Install Process
Setting up repositories
base

100% |=========================| 1.1 kB 00:00


updates

100% |=========================|

951 B 00:00


addons

100% |=========================|

951 B 00:00


extras

100% |=========================| 1.1 kB 00:00


Loading mirror speeds from cached hostfile
Reading repository metadata in from local files
Parsing package install arguments
Resolving Dependencies
–> Populating transaction set with selected packages. Please wait.
—> Downloading header for php to pack into transaction set.
php-5.1.6-7.el5.i386.rpm

100% |====================| 17 kB 00:00


—> Package php.i386 0:5.1.6-7.el5 set to be updated
—> Downloading header for httpd to pack into transaction set.
httpd-2.2.3-6.el5.centos.

100% |====================| 54 kB 00:00


—> Package httpd.i386 0:2.2.3-6.el5.centos.1 set to be updated
—> Downloading header for php-mbstring to pack into transaction set.
php-mbstring-5.1.6-7.el5.

100% |====================| 16 kB 00:00


—> Package php-mbstring.i386 0:5.1.6-7.el5 set to be updated
—> Downloading header for mod_ssl to pack into transaction set.
mod_ssl-2.2.3-6.el5.cento

100% |====================| 11 kB 00:00


—> Package mod_ssl.i386 1:2.2.3-6.el5.centos.1 set to be updated
—> Downloading header for php-pear to pack into transaction set.
php-pear-1.4.9-4.noarch.r

100% |====================| 20 kB 00:00


—> Package php-pear.noarch 1:1.4.9-4 set to be updated
–> Running transaction check
–> Processing Dependency: php-cli = 5.1.6-7.el5 for package: php
–> Processing Dependency: libnal.so.1 for package: mod_ssl
–> Processing Dependency: libdistcache.so.1 for package: mod_ssl
–> Processing Dependency: php-cli for package: php-pear
–> Processing Dependency: php-common = 5.1.6-7.el5 for package: php
–> Processing Dependency: php-common = 5.1.6-7.el5 for package: php-mbstring
–> Restarting Dependency Resolution with new changes.
–> Populating transaction set with selected packages. Please wait.
—> Downloading header for distcache to pack into transaction set.
distcache-1.4.5-14.1.i386

100% |====================| 8.8 kB 00:00


—> Package distcache.i386 0:1.4.5-14.1 set to be updated
—> Downloading header for php-common to pack into transaction set.
php-common-5.1.6-7.el5.i3

100% |=====================| 19 kB 00:00


—> Package php-common.i386 0:5.1.6-7.el5 set to be updated
—> Downloading header for php-cli to pack into transaction set.
php-cli-5.1.6-7.el5.i386.

100% |=====================| 17 kB 00:00


—> Package php-cli.i386 0:5.1.6-7.el5 set to be updated
–> Running transaction check

Dependencies Resolved

===========================================================
Package

Arch

Version

  Repository

Size


===========================================================
Installing:
httpd

i386

2.2.3-6.el5.centos.1

    base

1.1 M


mod_ssl

i386

1:2.2.3-6.el5.centos.1

    base

84 k


php

i386

5.1.6-7.el5

    updates

1.2 M


php-mbstring

i386

5.1.6-7.el51

    updates

966 k


php-pear

noarch

1:1.4.9-4

    base

355 k


Installing for dependencies:
distcache

i386

1.4.5-14.1

    base

119 k


php-cli

i386

5.1.6-7.el5

    updates

2.2 M


php-common

i386

5.1.6-7.el5

    updates

139 k

Transaction Summary
===========================================================
Install

8 Package(s)


Update

0 Package(s)


Remove

0 Package(s)

Total download size: 6.2 M
Downloading Packages:
(1/8): distcache-1.4.5-14

100% |====================| 119 kB 00:00


(2/8): php-pear-1.4.9-4.n

100% |====================| 355 kB 00:00


(3/8): mod_ssl-2.2.3-6.el

100% |====================|

84 kB 00:00


(4/8): php-mbstring-5.1.6

100% |====================| 966 kB 00:00


(5/8): php-common-5.1.6-7

100% |====================| 139 kB 00:00


(6/8): php-cli-5.1.6-7.el

100% |====================|

2.2 MB 00:00


(7/8): php-5.1.6-7.el5.i3

100% |====================|

1.2 MB 00:00


(8/8): httpd-2.2.3-6.el5.

100% |====================|

1.1 MB 00:00


Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
Installing:   php-common

#################################### [1/8]


Installing:   php-cli

#################################### [2/8]


Installing:   httpd

#################################### [3/8]


Installing:   php

#################################### [4/8]


Installing:   distcache

#################################### [5/8]


Installing:   php-pear

#################################### [6/8]


Installing:   mod_ssl

#################################### [7/8]


Installing:   php-mbstring

#################################### [8/8]

Installed: httpd.i386 0:2.2.3-6.el5.centos.1 mod_ssl.i386 1:2.2.3-6.el5.centos.1 php.i386 0:5.1.6-7.el5 php-mbstring.i386 0:5.1.6-7.el5 php-pear.noarch 1:1.4.9-4
Dependency Installed: distcache.i386 0:1.4.5-14.1 php-cli.i386 0:5.1.6-7.el5 php-common.i386 0:5.1.6-7.el5
Complete!
[root@www ~]#
[root@www ~]#

rm -f /etc/httpd/conf.d/welcome.conf


[root@www ~]#
[root@www ~]#

rm -f /var/www/error/noindex.html


[root@www ~]#

ln -s /usr/bin/perl /usr/local/bin/perl


[root@www ~]#

Apache + MySQL + PHP

1. Installing Apache + PHP

Apache is one of the most famous web server which runs on most linux based servers. With just few commands you can configure apache to run with PHP 4 or PHP 5.

If you want to install PHP 4, just apt-get

apt-get install apache2 php4 libapache2-mod-php4

To install PHP5, just run the following on linux shell. Note that if you dont specify packages with ‘4′, PHP5 will be automatically installed.

apt-get install apache2 php5 libapache2-mod-php5

Apache configuration file is located at: /etc/apache2/apache2.conf and your web folder is /var/www

To check whether php is installed and running properly, just create a test.php in your /var/www folder with phpinfo() function exactly as shown below.

nano /var/www/test.php

# test.php

<?php phpinfo(); ?>

Point your browser to http://ip.address/test.php or http://domain/test.php and this should show all your php configuration and default settings.

You can edit necessary values or setup virtual domains using apache configuration file.

Enabling GD Library with PHP

If you want to use CAPTCHA or for dynamic image generation with php scripts for image verification to stop SPAM or automated robots, then it is absolutely necessary to get php gd library installed with php. Here is the command

apt-get install php5-gd

Thats it!! Point your browser to http://domain/test.php and the php configuration settings will show GD library will be enabled for PNG, GIF, JPG etc.

Enabling Mod Rewrite with .htaccess

Do you use mod-rewrite from apache to rewrite friendly URLs ?? This must be absolutely necessary for the rewrite module to get enabled in your apache, especially if your blog, forum script uses rewriting engine to generate friendly URLs in your site. Note that default apache2 installation does not come with mod-rewrite. Here is how you enable it. Issue the following command

# a2enmod rewrite

Once you run this command, apache will tell you that this rewrite module is enabled. You can find mod_rewrite enabled and show up in your test.php file.

I often experienced page not found 404 error with debian/ubuntu versions eventhough your apache runs with mod-rewrite. To fix this, you will need to edit the following file to make some changes.

nano /etc/apache2/sites-enabled/000-default

Find the following and change AllowOverride from None to All

<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride
All
Order allow,deny
allow from all
# Uncomment this directive is you want to see apache2’s
# default start page (in /apache2-default) when you go to /
#RedirectMatch ^/$ /apache2-default/
</Directory>

Upload the .htaccess file to your server and restart apache. /etc/init.d/apache2 restart

Make sure your .htaccess file has 644 permission as otherwise you get permission denied error.

NOTE: I have often experienced .htaccess remaining invisible or disappearing problem when i uploaded any dotted files in the server (like .htaccess .ftpquota). Actually FTP clients do write .htaccess file but they do not show up when you upload. This happened with me using VSFTP. Here is how you fix

2. Installing MySQL Database Server

Installing mysql database server is always necessary if you are running a database driven ecommerce site. Remember running mysql server to a fair extend requires atleast 256mb of RAM in your server. So unless you are running database driven sites you dont absolutely need mysql. The following commands will install mysql 5 server and mysql 5 client.

apt-get install mysql-server mysql-client php5-mysql

Note: If you have already installed php4, you should make a slight change like this.

apt-get install mysql-server mysql-client php4-mysql

The configuration file of mysql is located at: /etc/mysql/my.cnf

Creating users to use MySQL and Changing Root Password

By default mysql creates user as root and runs with no passport. You might need to change the root password.

To change Root Password

mysql> USE mysql;
mysql> UPDATE user SET Password=PASSWORD(‘new-password’) WHERE user=’root’;
mysql> FLUSH PRIVILEGES;

To Create User

You must never use root password, so you might need to create a user to connect to mysql database for a PHP script. Alternatively you can add users to mysql database by using a control panel like webmin or phpMyAdmin to easily create or assign database permission to users. We will install Webmin and phpmyadmin during later once we complete basic mail LAMP installation.

PhpMyAdmin Installation

PhpMyAdmin is a nice web based database management and administration software and easy to install and configure under apache. Managing databases with tables couldnt be much simpler by using phpmyadmin.

All you need to do is:

apt-get install phpmyadmin

The phpmyadmin configuration file is located at: /etc/phpmyadmin folder.

To setup under apache all you need to do is include the following line in /etc/apache2/apache2.conf

Include /etc/phpmyadmin/apache.conf

Now restart apache: /etc/init.d/apache2 restart

Point your browser to: http://domain/phpmyadmin

Thats it!! MySQL and phpMyAdmin is Ready !!! Login with your mysql root password and create users to connect to database from your php script.