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?
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.
require_auth
environment variable is not set, there is no need for authentication. The SetEnvIfNoCase
directives at the top sets that variable if the request is for certain directories (whether they exist or not). –
Freezedry 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>'
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.
© 2022 - 2024 — McMap. All rights reserved.