Marius van Witzenburg We fight for our survival, we fight!

6Jul/110

How to generate a .htaccess and .htpasswd with PHP

Posted by mariusvw

Ever had a moment where you needed to secure a directory but didn't have the htpasswd tool available?

The following script simply generates a .htaccess and .htpasswd file to secure a directory.

<!DOCTYPE html>
<html>
<body>
<?php if (!empty($_POST['username']) && !empty($_POST['password'])): ?>
<strong>.htaccess</strong><br>
<pre>
AuthName "Members only"
AuthType Basic
AuthUserFile /srv/www/domain.tld/.htpasswd
require valid-user
</pre> 
Save the above file in the directory you want to secure.<br>
<br>
<strong>.htpasswd</strong><br>
<pre>
<?php echo $_POST['username'] . ':' . crypt($_POST['password'], base64_encode($_POST['password'])); ?>
</pre>
Save the above file as <strong>/srv/www/domain.tld/.htpasswd</strong>.<br>
<br>
<a href="<?php echo $_SERVER['PHP_SELF']; ?>">&laquo; BACK &laquo;</a>
<?php else: ?>
<form method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit">
</form>
</form>
<?php endif; ?>
</body>
</html>
30Jun/100

How to force your visitors to goto your website domain without www as a prefix with mod_rewrite in Apache

Posted by mariusvw

Actually this is quite simple, you need to create a .htaccess file into your public_html / httpdocs directory and add the following piece of code:

Force non-www

# Force non-www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^kitara.nl
RewriteRule (.*) http://kitara.nl/$1 [R=301,L]

Force www

# Force www
RewriteCond %{HTTP_HOST} !^www.kitara.nl
RewriteRule (.*) http://www.kitara.nl/$1 [R=301,L]

Of course you need to modify this to match your own domain name :-)