Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to specific page if not logged in with .htaccess

I am running apache2 and php5 in my Windows PC.

I have protected my directory using .htaccess and.htpasswd. If login information is not set, or if the username-password combination is not correct, the browser will prompt for a username and password box by default, if user tries to access protected dir.

But I want to redirect the user to a specific address or url. In short, I want to redirect user instead of displaying the HTTP basic authentication dialog. How can I make this possible?

like image 644
Alfred Avatar asked Apr 21 '11 17:04

Alfred


1 Answers

I got this to work with an approach similar to AJ's. My .htaccess file is very similar to the following:

AuthUserFile /opt/www/htaccess
AuthType Basic

DirectoryIndex public.txt

<Files "secret.txt">
    require valid-user
    FileETag None
    Header unset ETag
    Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</Files>

<Files "public.txt">
    FileETag None
    Header unset ETag
    Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</Files>

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP:Authorization} !=""
RewriteRule ^$ secret.txt [L]

With this, the site behaves as follows:

1) Access the base URL -> see content from public.txt. 2) Access /secret.txt -> prompted to authenticate, and shown the contents of secret.txt. 3) Access the base URL again -> see content from secret.txt.

Using [L,R] instead of [L] will use a 302 response to handle the redirection. This is a good option if you want the redirection to be visible in the browser's location field.

<aside>Yes, I realize that this is a very late answer. The question was high in the Google search results, though, so I wanted to detail my approach in case I find myself doing the same search in the future. If anyone else benefits, it's even better.</aside>

like image 152
GargantuChet Avatar answered Nov 14 '22 23:11

GargantuChet