Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess, mod_rewrite, and basic authentication

I am working on a Wordpress site, and my pages are using a permalink structure that mod_rewrites them to look like directories. For a few pages I want to use Basic Authentication to password protect a few of the pages. How would I write this in my .htaccess file? Am I protecting the file, or the rewritten address?

like image 745
Imaginary Avatar asked Aug 30 '12 19:08

Imaginary


3 Answers

You won't need mod_rewrite for this, hopefully, this should do the trick:

SetEnvIfNoCase Request_URI ^/some/path/to/protect require_auth=true
SetEnvIfNoCase Request_URI ^/another/protected/path require_auth=true

# Auth stuff
AuthUserFile /var/www/htpasswd
AuthName "Password Protected"
AuthType Basic

# Setup a deny/allow
Order Deny,Allow
# Deny from everyone
Deny from all
# except if either of these are satisfied
Satisfy any
# 1. a valid authenticated user
Require valid-user
# or 2. the "require_auth" var is NOT set
Allow from env=!require_auth

The mod_auth and mod_env modules should have precidence over mod_rewrite, so your fake directory structure should stay the same. You'd just need to fill out a SetEnvIfNoCase Request_URI ^/some/path/to/protect require_auth=true for each one, then fill out the rest of the auth stuff to suit your needs.

like image 57
Jon Lin Avatar answered Nov 14 '22 00:11

Jon Lin


The only problem I have with this solution is that clicking the cancel button will show the protected page. I tried to solve this by using:

RewriteCond %{REMOTE_USER} !user
RewriteRule ^/protected-page /unauthenticated-page [R=401]

But that didn't work. I'm not sure why.

To solve the problem quick and dirty I added

ErrorDocument 401 "You don't have access."

To create a redirect I used this

ErrorDocument 401 '<html><head><meta http-equiv="refresh" content="0; url=/unauthenticated-page" /></head><body></body></html>'
like image 23
Martijn Gastkemper Avatar answered Nov 13 '22 23:11

Martijn Gastkemper


For those who came here with same problem as me, with .htaccess like this

AuthType Basic
AuthName "some_name"
AuthUserFile "/path/to/password/passwd"
require valid-user
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

rules above are not working as I expected (authorize, then rewrite)

because of directive merging order ("If" is merged last)

thanks to comment from Alek to point that out

so when I removed IfModule brackets, the rules have begun to work for me.

like image 1
Арсен Сиреканян Avatar answered Nov 13 '22 22:11

Арсен Сиреканян