Tutorial
Introduction
Apache is a popular web server software which is developed and maintained by The Apache Software foundation in the Uinted States. It is a non-profit organization to support various projects handled by the Apache software, Including the Apache server. Majority of the web servers in the world are run by Apache Software. Majority of web servers around the world use Apache or Apache HTTP Server software. Apache is an open source software developed and maintained by the Apache Software Foundation. It is quite fast, secure and can be customized easily for different environments by using extensions and modules.
When setting up a web server, there are often sections of the site that you wish to restrict access to. Web applications often provide their own authentication and authorization methods, but the web server itself can be used to restrict access if these are inadequate or unavailable.
In this guide, we’ll demonstrate how to password protect assets on an Apache web server running on Ubuntu 14.04.
Prerequisites
- The Apache web server is easy to install. With one command, you can install it and all necessary dependencies: $ dnf install httpd All the configuration files for Apache are located in /etc/httpd/conf and /etc/httpd/conf.d.
- A virtual machine instance on Google Compute Engine can be controlled like any standard Linux server. Deploy a simple Apache web server to learn the basics of running a server on a virtual machine.
To get started, you will need access to an Ubuntu 14.04 server environment. You will need a non-root user with sudo
privileges in order to perform administrative tasks. To learn how to create such a user, follow our Ubuntu 14.04 initial server setup guide.
Install the Apache Utilities Package
In order to create the file that will store the passwords needed to access our restricted content, we will use a utility called htpasswd
. This is found in the apache2-utils
package within the Ubuntu repositories.
Update the local package cache and install the package by typing this command. We will take this opportunity to also grab the Apache2 server in case it is not yet installed on the server:
Create the Password File
We now have access to the htpasswd
command. We can use this to create a password file that Apache can use to authenticate users. We will create a hidden file for this purpose called .htpasswd
within our /etc/apache2
configuration directory.
The first time we use this utility, we need to add the -c
option to create the specified file. We specify a username (sammy
in this example) at the end of the command to create a new entry within the file:
About Apache Web Server
You will be asked to supply and confirm a password for the user.
Leave out the -c
argument for any additional users you wish to add:
If we view the contents of the file, we can see the username and the encrypted password for each record:
Configure Apache Password Authentication
Now that we have a file with our users and passwords in a format that Apache can read, we need to configure Apache to check this file before serving our protected content. We can do this in two different ways.
The first option is to edit the Apache configuration and add our password protection to the virtual host file. This will generally give better performance because it avoids the expense of reading distributed configuration files. If you have this option, this method is recommended.
If you do not have the ability to modify the virtual host file (or if you are already using .htaccess files for other purposes), you can restrict access using an
.htaccessfile. Apache uses
.htaccess` files in order to allow certain configuration items to be set within a file in a content directory. The disadvantage is that Apache has to re-read these files on every request that involves the directory, which can impact performance.
Choose the option that best suits your needs below.
Configuring Access Control within the Virtual Host Definition
Begin by opening up the virtual host file that you wish to add a restriction to. For our example, we’ll be using the 000-default.conf
file that holds the default virtual host installed through Ubuntu’s apache package:
Inside, with the comments stripped, the file should look similar to this:
Authentication is done on a per-directory basis. To set up authentication, you will need to target the directory you wish to restrict with a <Directory ___>
block. In our example, we’ll restrict the entire document root, but you can modify this listing to only target a specific directory within the web space:
Within this directory block, specify that we wish to set up Basic
authentication. For the AuthName
, choose a realm name that will be displayed to the user when prompting for credentials. Use the AuthUserFile
directive to point Apache to the password file we created. Finally, we will require a valid-user
to access this resource, which means anyone who can verify their identity with a password will be allowed in:
Save and close the file when you are finished. Restart Apache to implement your password policy:
The directory you specified should now be password protected.
Configuring Access Control with .htaccess Files
If you wish to set up password protection using .htaccess
files instead, you should begin by editing the main Apache configuration file to allow .htaccess
files:
Find the <Directory>
block for the /var/www
directory that holds the document root. Turn on .htaccess
processing by changing the AllowOverride
directive within that block from “None” to “All”:
Save and close the file when you are finished.
About Apache Web Servers
Next, we need to add an .htaccess
file to the directory we wish to restrict. In our demonstration, we’ll restrict the entire document root (the entire website) which is based at /var/www/html
, but you can place this file in any directory you wish to restrict access to:
Within this file, specify that we wish to set up Basic
authentication. For the AuthName
, choose a realm name that will be displayed to the user when prompting for credentials. Use the AuthUserFile
directive to point Apache to the password file we created. Finally, we will require a valid-user
to access this resource, which means anyone who can verify their identity with a password will be allowed in:
Save and close the file. Restart the web server to password protect all content in or below the directory with the .htaccess
file:
Confirm the Password Authentication
To confirm that your content is protected, try to access your restricted content in a web browser. You should be presented with a username and password prompt that looks like this:
If you enter the correct credentials, you will be allowed to access the content. If you enter the wrong credentials or hit “Cancel”, you will see the “Unauthorized” error page:
Conclusion
You should now have everything you need to set up basic authentication for your site. Keep in mind that password protection should be combined with SSL encryption so that your credentials are not sent to the server in plain text. To learn how to create a self-signed SSL certificate to use with Apache, follow this guide. To learn how to install a commercial certificate, follow this guide.
What is Apache
Apache is the most widely used web server software. Developed and maintained by Apache Software Foundation, Apache is an open source software available for free.. It is fast, reliable, and secure. It can be highly customized to meet the needs of many different environments by using extensions and modules. Most hosting providers companies use Apache as their web server software.
Apache Most Features
Unix Threading
On Unix systems with POSIX threads support, Apache httpd can now run in a hybrid multiprocess, multithreaded mode. This improves scalability for many, but not all configurations.
New Build System
The build system has been rewritten from scratch to be based on autoconf and libtool. This makes Apache httpd’s configuration system more similar to that of other packages.
Multiprotocol Support
Apache HTTP Server now has some of the infrastructure in place to support serving multiple protocols. mod_echo has been written as an example.
Better support for non-Unix platforms
Apache HTTP Server 2.0 is faster and more stable on non-Unix platforms such as BeOS, OS/2, and Windows. With the introduction of platform-specific multi-processing modules (MPMs) and the Apache Portable Runtime (APR), these platforms are now implemented in their native API, avoiding the often buggy and poorly performing POSIX-emulation layers.
New Apache httpd API
About Apache Tomcat Web Server
The API for modules has changed significantly for 2.0. Many of the module-ordering/-priority problems from 1.3 should be gone. 2.0 does much of this automatically, and module ordering is now done per-hook to allow more flexibility. Also, new calls have been added that provide additional module capabilities without patching the core Apache HTTP Server.
IPv6 Support
On systems where IPv6 is supported by the underlying Apache Portable Runtime library, Apache httpd gets IPv6 listening sockets by default. Additionally, the Listen, NameVirtualHost, and VirtualHost directives support IPv6 numeric address strings (e.g., “Listen [2001:db8::1]:8080”).
Apache Filtering
Apache httpd modules may now be written as filters which act on the stream of content as it is delivered to or from the server. This allows, for example, the output of CGI scripts to be parsed for Server Side Include directives using the INCLUDES filter in mod_include. The module mod_ext_filter allows external programs to act as filters in much the same way that CGI programs can act as handlers.
Multilanguage Error Responses
Error response messages to the browser are now provided in several languages, using SSI documents. They may be customized by the administrator to achieve a consistent look and feel.
Simplified configuration
Many confusing directives have been simplified. The often confusing Port and BindAddress directives are gone; only the Listen directive is used for IP address binding; the ServerName directive specifies the server name and port number only for redirection and vhost recognition.
Native Windows NT Unicode Support
Apache httpd 2.0 on Windows NT now uses utf-8 for all filename encodings. These directly translate to the underlying Unicode file system, providing multilanguage support for all Windows NT-based installations, including Windows 2000 and Windows XP. This support does not extend to Windows 95, 98 or ME, which continue to use the machine’s local codepage for filesystem access.
Regular Expression Library Updated
Apache httpd 2.0 includes the Perl Compatible Regular Expression Library (PCRE). All regular expression evaluation now uses the more powerful Perl 5 syntax.
Apache Most Module
- mod_proxy_fcgi : FastCGI Protocol backend for mod_proxy
- mod_proxy_scgi : SCGI Protocol backend for mod_proxy
- mod_proxy_express : Provides dynamically configured mass reverse proxies for mod_proxy
- mod_remoteip: Replaces the apparent client remote IP address and hostname for the request with the IP address list presented by a proxies or a load balancer via the request headers.
- mod_heartmonitor, mod_lbmethod_heartbeat:Allow mod_proxy_balancer to base loadbalancing decisions on the number of active connections on the backend servers.
- mod_proxy_html:Formerly a third-party module, this supports fixing of HTML links in a reverse proxy situation, where the backend generates URLs that are not valid for the proxy’s clients.
- mod_sed : An advanced replacement of mod_substitute, allows to edit the response body with the full power of sed.
- mod_auth_form: Enables form-based authentication.
- mod_session : Enables the use of session state for clients, using cookie or database storage.
- mod_allowmethods: New module to restrict certain HTTP methods without interfering with authentication or authorization.
- mod_lua: Embeds the Lua language into httpd, for configuration and small business logic functions. (Experimental)
- mod_log_debug: Allows the addition of customizable debug logging at different phases of the request processing.
- mod_buffer: Provides for buffering the input and output filter stacks
- mod_data : Convert response body into an RFC2397 data URL
- mod_ratelimit : Provides Bandwidth Rate Limiting for Clients
- mod_request : Provides Filters to handle and make available HTTP request bodies
- mod_reflector : Provides Reflection of a request body as a response via the output filter stack.
- mod_slotmem_shm : Provides a Slot-based shared memory provider (ala the scoreboard).
- mod_xml2enc : Formerly a third-party module, this supports internationalisation in libxml2-based (markup-aware) filter modules.
- mod_macro :(available since 2.4.5) Provide macros within configuration files.
- mod_proxy_wstunnel : (available since 2.4.5) Support web-socket tunnels.
- mod_authnz_fcgi : (available since 2.4.10) Enable FastCGI authorizer applications to authenticate and/or authorize clients.
- mod_http2 : (available since 2.4.17) Support for the HTTP/2 transport layer.
- mod_ssl : mod_ssl can now be configured to use an OCSP server to check the validation status of a client certificate. The default responder is configurable, along with the decision on whether to prefer the responder designated in the client certificate itself. mod_ssl now also supports OCSP stapling, where the server pro-actively obtains an OCSP verification of its certificate and transmits that to the client during the handshake .mod_ssl can now be configured to share SSL Session data between servers through memcached EC keys are now supported in addition to RSA and DSA. Support for TLS-SRP (available in 2.4.4 and later).
- mod_proxy: The ProxyPass directive is now most optimally configured within a Location or LocationMatch block, and offers a significant performance advantage over the traditional two-parameter syntax when present in large numbers. The source address used for proxy requests is now configurable. Support for Unix domain sockets to the backend (available in 2.4.7 and later).
- mod_proxy_balancer: More runtime configuration changes for BalancerMembers via balancer-manager Additional BalancerMembers can be added at runtime via balancer-manager Runtime configuration of a subset of Balancer parameters BalancerMembers can be set to ‘Drain’ so that they only respond to existing sticky sessions, allowing them to be taken gracefully offline. Balancer settings can be persistent after restarts.
- mod_cache: The mod_cache CACHE filter can be optionally inserted at a given point in the filter chain to provide fine control over caching. mod_cache can now cache HEAD requests. Where possible, mod_cache directives can now be set per directory, instead of per server. The base URL of cached URLs can be customised, so that a cluster of caches can share the same endpoint URL prefix. mod_cache is now capable of serving stale cached data when a backend is unavailable (error 5xx). mod_cache can now insert HIT/MISS/REVALIDATE into an X-Cache header.
- mod_include : Support for the ‘onerror’ attribute within an ‘include’ element, allowing an error document to be served on error instead of the default error string.
- mod_cgi, mod_include, mod_isapi :Translation of headers to environment variables is more strict than before to mitigate some possible cross-site-scripting attacks via header injection. Headers containing invalid characters (including underscores) are now silently dropped. Environment Variables in Apache has some pointers on how to work around broken legacy clients which require such headers. (This affects all modules which use these environment variables.).
- mod_authz_core :Authorization Logic Containers Advanced authorization logic may now be specified using the Require directive and the related container directives, such as <RequireAll>.
- mod_rewrite:mod_rewrite adds the [QSD] (Query String Discard) and [END] flags for RewriteRule to simplify common rewriting scenarios.Adds the possibility to use complex boolean expressions in RewriteCond.Allows the use of SQL queries as RewriteMap functions.
- mod_ldap, mod_authnz_ldap :mod_authnz_ldap adds support for nested groups.mod_ldap adds LDAPConnectionPoolTTL, LDAPTimeout, and other improvements in the handling of timeouts. This is especially useful for setups where a stateful firewall drops idle connections to the LDAP server.
mod_ldap adds LDAPLibraryDebug to log debug information provided by the used LDAP toolkit. - mod_info :mod_info can now dump the pre-parsed configuration to stdout during server startup.
- mod_auth_basic:New generic mechanism to fake basic authentication (available in 2.4.5 and later).
Categories
- Apache (6)
- CloudLinux (2)
- cPanel (3)
- DirectAdmin (2)
- Domains (11)
- General Topics (22)
- Install SSL Certificate (12)
- Linux (40)
- Manage Emails (6)
- MS SQL Server (1)
- MySQL (6)
- PHP (3)
- Plesk Control Panel (16)
- SSL Certificates (23)
- Support (1)
- Technical Support (6)
- Web Security (2)
- WHM/cPanel (56)
- Windows Server (5)
- Windows Server IIS (1)