I’m working on blocking a folder with .htaccess, which I’ve never used before, and I’m having some trouble. Here’s what I have
.htaccess (located in the folder I want blocked):
AuthName "Username and password required"
AuthUserFile /.htpasswd
Require valid-user
AuthType Basic
.htpasswd (located at root, password is encrypted in actual file):
tim:blah
I’m getting 500 Internal Server errors with this and I can’t figure out why.
asked Sep 27, 2013 at 21:46
3
Most likely problem is this line:
AuthUserFile /.htpasswd
This line should provide full filesystem path to the password file e.g.
AuthUserFile /var/www/.htpasswd
To discover your filesystem path, you can create a PHP document containing
echo $_SERVER['DOCUMENT_ROOT'];
Chuck Le Butt
47.6k62 gold badges203 silver badges289 bronze badges
answered Sep 27, 2013 at 21:54
anubhavaanubhava
762k64 gold badges570 silver badges644 bronze badges
7
If nothing helped and you’re using PHP you can make it work by putting this in your index.php (on top):
if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
if ($_SERVER['PHP_AUTH_USER'] !== 'user' ||
$_SERVER['PHP_AUTH_PW'] !== 'pass') {
header('WWW-Authenticate: Basic realm="Protected area"');
header('HTTP/1.0 401 Unauthorized');
die('Login failed');
}
}
answered Dec 5, 2014 at 20:11
ArneArne
6,1502 gold badges21 silver badges20 bronze badges
Permissions can cause this issue too.
Make sure .htpasswd
is readable by the web server user.
For instance, if you use nginx check the nginx.conf
to find out what the server user is, if you use Apache you can find it out this way, etc.
Then set the right owners and read permissions to .htpasswd
answered Sep 19, 2014 at 23:22
OriolOriol
11.7k5 gold badges35 silver badges37 bronze badges
If you see 500 Internal Server error
these days — it’s mostly due to the fact that in newer Apache versions the path in AuthUserFile
has to be put inside quotation marks
.
AuthUserFile "/var/www/somewhere/.htpasswd"
answered Sep 11, 2020 at 10:39
HexodusHexodus
12.4k6 gold badges53 silver badges73 bronze badges
1
I would also add that some on some Web hosts, the .htpasswd file will not work if placed in a publicly accessible area. A recent installation I did confirmed this. As others have noted, it’s best to place this in the root of the site.
answered May 26, 2015 at 6:34
karoluskarolus
9127 silver badges13 bronze badges
1
Had the same problem, it had to do with access! Have you given ownership of the password file to www-data
user through
chown www-data /var/www/.htpasswd
chmod 640 /var/www/.htpasswd
? It’s best to keep the password, for obvious reasons, to keep the password somewhere outside the /var/www/
directory, let’s say /home/MYSERVER/
in such a case you also need to give ownership of this parent directory to the user www-data
.
answered Jun 18, 2019 at 16:40
I have got same problem on Apache/2.4.6 (CentOS).
It turned out that Apache has some bug (https://bz.apache.org/bugzilla/show_bug.cgi?id=54735), and you need to set password from console like this:
htpasswd -nb username newpassw > <path-to>/.htpasswd
answered Feb 3 at 13:30
Solved in .htaccess remove quote » and write full path for AuthUserFile then it will work.
Tested on xampp
AuthName "Restricted Area"
AuthType Basic
AuthUserFile C:/xampp/htdocs/.htpasswd
AuthGroupFile /
Require valid-user
.htpasswd
foo:bar
answered Jul 26 at 20:49
HakanHakan
2584 silver badges4 bronze badges
I just edited the .htaccess
file to include:
AuthType Basic
AuthName "My Protected Area"
AuthUserFile /home/path/to/public_html/
Require valid-user
I then created a .htpasswd
file via the htpasswd
command. I have enabled the module: LoadModule authn_file_module modules/mod_authn_file.so
in the Apache configuration.
Now, when I load the page I get a 500 error and Apache log says:
configuration error: couldn’t check user. No user file?: /
MrWhite
12.7k4 gold badges29 silver badges41 bronze badges
asked Jan 6, 2011 at 15:00
2
The AuthUserFile
command is provided by the mod_authn_file
module. Make sure your Apache configuration includes something along the lines of:
LoadModule authn_file_module modules/mod_authn_file.so
This would need to go into the main server configuration, not in a .htaccess
file. If you don’t have access to the main server configuration you’ll need to contact your local administrator.
answered Jan 6, 2011 at 15:06
larskslarsks
43.7k14 gold badges122 silver badges181 bronze badges
5
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
I’ve created a .htaccess and a .htpasswd file, both using my hosting’s tool, uploaded them, and I get an error when I try to view the directory. Why?
my .htaccess file:
AuthName "Restricted Area"
AuthType Basic
AuthUserFile /home/u947248131/.htpasswd
AuthGroupFile /dev/null
require valid-user
asked Apr 27, 2013 at 18:25
in your .htaccess file is it within
<Directory /path/to/the/directory >
AuthName "Restricted Area" AuthType Basic AuthUserFile /home/u947248131/.htpasswd AuthGroupFile /dev/null require valid-user</Directory>
More help http://httpd.apache.org/docs/2.2/howto/auth.html#gettingitworking
Otherwise if you can put the error log that would help
answered Apr 27, 2013 at 21:21
-
#1
Hello,
I am using vanilla install of
Plesk Onyx- Version 17.5.3 Update #12, last updated on July 4, 2017 01:32 PM
Ubuntu 16.04.2 LTS 64bit
I want to password protect WordPress file wp-login.php which works fine on friends shared hosting
however when I apply adjusted settings to Plesk, it doesn’t work
added to top of .htaccess file (vanilla WordPress install)
Code:
# Protect wp-login
<Files wp-login.php>
AuthUserFile /absolute/path/to-this-file/user-domain.com/.htpasswd
AuthName "restricted access"
AuthType Basic
require user test1
</Files>
Htpasswd Generator – Create htpasswd — Htaccess Tools
.htpasswd created with values
Code:
test1:$apr1$9uo/rj2q$t7Jf1aYZVMPokc4FPtGyJ/
I have tried both Apache and NGINX, on NGINX it doesn’t work at all
-
#3
thank you @UFHH01
problem is resolved
here is how to prevent HTTP auth and allow only HTTPS auth
Code:
# Protect wp-login
<Files wp-login.php>
SSLRequireSSL
ErrorDocument 403 https://your-domain.com/wp-login.php
AuthType Basic
AuthName "restricted access"
AuthUserFile /absolute-path-format/your-domain.com/.htpasswd
Require valid-user
</Files>
-
#4
I have just tested this rule for Nginx — unfortunatelly it doesn’t work with Plesk Onyx 17.5
do you have idea why ?
here is my Apache & nginx Settings for that domain
Code:
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf)$ {expires 30d;}
if (!-e $request_filename) {
set $test P;
}
if ($uri !~ ^/(plesk-stat|webstat|webstat-ssl|ftpstat|anon_ftpstat|awstats-icon|internal-nginx-static-location)) {
set $test "${test}C";
}
if ($test = PC) {
rewrite ^/(.*)$ /index.php?$1;
}
# Disallow access to important files for ngninx
location ~* (/\.|wp-config\.php|(?<!robots)\.txt|(liesmich|readme).*) {
return 444;
}
# Auth protection to wp-login.php for nginx
location = /wp-login.php {
auth_basic "Restricted Admin-Area";
auth_basic_user_file /var/www/vhosts/my-subscription/my-domain.com/.htpasswd;
include /etc/nginx/fastcgi.conf;
}
after Login form, PHP is «downloaded» and not processed
I would like to use Ngnix, thank you
Last edited:
Я работаю над блокировкой папки с помощью .htaccess, которую я никогда раньше не использовал, и у меня возникли проблемы. Вот что у меня есть
.htaccess (находится в папке, которую я хочу заблокировать):
AuthName "Username and password required"
AuthUserFile /.htpasswd
Require valid-user
AuthType Basic
.htpasswd (находится в корневом каталоге, пароль зашифрован в реальном файле):
tim:blah
Я получаю 500 ошибок внутреннего сервера и не могу понять почему.
person
Tim Aych
schedule
27.09.2013
source
источник
Ответы (6)
Скорее всего проблема в этой строке:
AuthUserFile /.htpasswd
В этой строке должен быть указан полный путь файловой системы к файлу паролей, например.
AuthUserFile /var/www/.htpasswd
Чтобы узнать путь к вашей файловой системе, вы можете создать документ PHP, содержащий
echo $_SERVER['DOCUMENT_ROOT'];
person
anubhava
schedule
27.09.2013
Если ничего не помогло и вы используете PHP, вы можете заставить его работать, поместив это в свой index.php (вверху):
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
if ($_SERVER['PHP_AUTH_USER'] != 'user' ||
$_SERVER['PHP_AUTH_PW'] != 'pass') {
header('WWW-Authenticate: Basic realm="Protected area"');
header('HTTP/1.0 401 Unauthorized');
die('Login failed!');
}
}
person
Arne
schedule
05.12.2014
Разрешения тоже могут вызвать эту проблему.
Убедитесь, что .htpasswd
доступен для чтения пользователю веб-сервера.
Например, если вы используете nginx, проверьте nginx.conf
, чтобы узнать, что такое пользователь сервера, если вы используете Apache, вы можете узнать его таким образом и т. д.
Затем установите правообладателей и права на чтение .htpasswd
person
Oriol
schedule
19.09.2014
Если вы видите 500 Internal Server error
в наши дни — это в основном из-за того, что в новых версиях Apache путь в AuthUserFile
должен быть помещен внутри quotation marks
.
AuthUserFile "/var/www/somewhere/.htpasswd"
person
Hexodus
schedule
11.09.2020
Я бы также добавил, что на некоторых веб-хостах файл .htpasswd не будет работать, если он будет размещен в общедоступной области. Недавняя установка, которую я сделал, подтвердила это. Как отмечали другие, лучше всего разместить это в корне сайта.
person
karolus
schedule
26.05.2015
Была такая же проблема, это было связано с доступом! Передали ли вы право владения файлом паролей www-data
пользователю через
chown www-data /var/www/.htpasswd
chmod 640 /var/www/.htpasswd
? По очевидным причинам лучше всего сохранить пароль, чтобы сохранить пароль где-то за пределами каталога /var/www/
, скажем /home/MYSERVER/
, в таком случае вам также необходимо передать право владения этим родительским каталогом пользователю www-data
.
person
Lab Nap
schedule
18.06.2019