apache exclude url from auth

How to Exclude URL from Auth in Apache

Apache allows you to setup basic authentication for your website. Sometimes you may need to exclude certain web pages from auth in Apache server. Here is how to exclude URL from Auth in Apache server.


How to Exclude URL from Auth in Apache

We will look at how to exclude URL from Auth in Apache using .htaccess file.


1. Enable mod_rewrite

If you have enabled mod_rewrite on your Apache server, you an skip these steps. Else run the following command depending on your Linux system.

Ubuntu/Debian

Open terminal and run the following command to enable mod_rewrite

$ sudo a2enmod rewrite

Redhat/Fedora/CentOS

Open Apache configuration file in a text editor.

$ sudo vi /etc/apache2/httpd.conf

Look for the following line.

#LoadModule rewrite_module modules/mod_rewrite.so

Uncomment it by removing # from its beginning. Add the above line if you can’t find it.

Also look for the following Directory tag and change AllowOverride from None to All.

. . .
<Directory /var/www/html>
. . .
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
. . .
</Directory>
. . .

Also read : How to Exclude Folder from Rewrite Rule in .htaccess


2. Update .htaccess

Let us say you want to exclude URL /sample.php from authentication. Create/Open .htaccess file in a text editor.

$ sudo vi /var/www/html/.htaccess

Add the following lines in it.

Apache 2.4

AuthType Basic
AuthName "Please login"
AuthUserFile "/etc/apache2/.htpasswd"

Require expr %{REQUEST_URI} =~ m#^/sample/.php#
Require valid-user

In the above block, the first 3 lines enable basic auth for your website. Line 4 enforces a condition that only URLs other than /sample.php need to be authenticated.

Apache <2.4

SetEnvIfNoCase Request_URI "^/sample\.php" noauth

AuthType Basic
AuthName "Please login"
AuthUserFile /etc/apache2/.htpasswd

Require valid-user
Order Deny,Allow
Deny from all
Allow from env=noauth
Satisfy any

In the above case, we basically tag /sample.php URL as noauth and then use Allow directive (line 10) to allow access to that URL.

Also read : How to Check Number of Concurrent Connections in Apache


3. Restart Apache Server

Restart Apache server to apply changes.

$ sudo service apache2 restart

In this article, we have learnt how to exclude specific URL from basic auth in Apache server.

Also read : How to Generate Subdomains on the Fly in Apache/PHP


Leave a Reply

Your email address will not be published. Required fields are marked *