I'd like to use multiple vhost templates from my apache module in my nodes manifest, and so far not having any luck.
I have one vhost template in my apache module that looks like this. This is my apache::vhost template:
cat modules/apache/templates/vhost.conf.erb
<VirtualHost *:<%= port %>>
ServerName <%= name %>
<%if serveraliases.is_a? Array -%>
<% serveraliases.each do |name| -%>
<%= " ServerAlias #{name}\n" %><% end -%>
<% elsif serveraliases != '' -%>
<%= " ServerAlias #{serveraliases}" -%>
<% end -%>
php_value newrelic.appname <%= name %>
KeepAlive On
KeepAliveTimeout 5
MaxKeepAliveRequests 100
LogFormat "{ \
\"host\":\"<%= name %>.<%= domain %>\", \
\"path\":\"/var/log/httpd/jf_<%= name %>_access_log\", \
\"tags\":[\"Jokefire <%= name %>\"], \
\"message\": \"%h %l %u %t \\\"%r\\\" %>s %b\", \
\"timestamp\": \"%{%Y-%m-%dT%H:%M:%S%z}t\", \
\"clientip\": \"%a\", \
\"duration\": %D, \
\"status\": %>s, \
\"request\": \"%U%q\", \
\"urlpath\": \"%U\", \
\"urlquery\": \"%q\", \
\"method\": \"%m\", \
\"bytes\": %B, \
\"vhost\": \"%v\" \
}" <%= name %>_access_json
CustomLog /var/log/httpd/jf_<%= name %>_access_log <%= name %>_access_json
LogLevel debug
ErrorLog /var/log/httpd/jf_<%= name %>_error_log
DirectoryIndex index.html index.php
DocumentRoot <%= docroot %>
<Directory <%= docroot %>>
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
allow from all
</Directory>
ServerSignature On
</VirtualHost>
And when I define that template in my nodes.pp manifest it worked totally fine:
apache::vhost { 'dev.example.com':
port => 80,
docroot => '/var/www/jf-wp',
ssl => false,
priority => 002,
}
But when I try to use another vhost template with different settings in my nodes.pp manifest I get an error. This is the apache::vhost_admin template that I can't get to work in my nodes.pp manifest:
#cat modules/apache/templates/vhost_admin.conf.erb
<VirtualHost *:<%= port %>>
ServerName <%= name %>
<%if serveraliases.is_a? Array -%>
<% serveraliases.each do |name| -%>
<%= " ServerAlias #{name}\n" %><% end -%>
<% elsif serveraliases != '' -%>
<%= " ServerAlias #{serveraliases}" -%>
<% end -%>
php_value newrelic.enabled false
KeepAlive On
KeepAliveTimeout 5
MaxKeepAliveRequests 100
LogFormat "{ \
\"host\":\"<%= name %>.<%= domain %>\", \
\"path\":\"/var/log/httpd/jf_<%= name %>_access_log\", \
\"tags\":[\"Jokefire <%= name %>\"], \
\"message\": \"%h %l %u %t \\\"%r\\\" %>s %b\", \
\"timestamp\": \"%{%Y-%m-%dT%H:%M:%S%z}t\", \
\"clientip\": \"%a\", \
\"duration\": %D, \
\"status\": %>s, \
\"request\": \"%U%q\", \
\"urlpath\": \"%U\", \
\"urlquery\": \"%q\", \
\"method\": \"%m\", \
\"bytes\": %B, \
\"vhost\": \"%v\" \
}" <%= name %>_access_json
CustomLog /var/log/httpd/jf_<%= name %>_access_log <%= name %>_access_json
LogLevel debug
ErrorLog /var/log/httpd/jf_<%= name %>_error_log
DirectoryIndex index.html index.php
DocumentRoot <%= docroot %>
<Directory <%= docroot %>>
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
allow from all
</Directory>
ServerSignature On
</VirtualHost>
And when I try to define apache::vhost_admin in my nodes.pp file:
apache::vhost_admin { 'admin.example.com':
port => 80,
docroot => '/var/www/admin',
ssl => false,
priority => 004,
serveraliases => 'www.admin.example.com',
}
When I define the apache::vhost_admin template in the nodes.pp manifest is when I get the following error:
Error: Could not retrieve catalog from remote server: Error 400 on SERVER: Puppet::Parser::AST::Resource failed with e
rror ArgumentError: Invalid resource type apache::vhost_admin at /etc/puppet/environments/production/manifests/nodes.p
p:139 on node web1.jokefire.com
Warning: Not using cache on failed catalog
Error: Could not retrieve catalog; skipping run
enter code here
What am I doing wrong? How can I define multiple vhost definitions in puppet, each with different settings?
After the discussion with #bluethundr, it looks like the "apache::vhost_admin" define was missing.
Related
I'm trying to install and run Django in a sub-directory, to isolate it and a static html site in root; these two questions haven't helped and are very old: install django on subdirectory and Configure django on sub directory
Is this a file/folder permissions, Apache user, virtualhosts or Python issue?
Why are the .py files not executing?
Outline:
I'm running Ubuntu 20.04.3 LTS
Apache2 was already installed and is running
Python3 and Django installed
libapache2-mod-wsgi-py3 installed and enabled
apachectl configtest Syntax OK
All files chowned to www-data:www-data
/var/log/apache2/access.log is empty
/var/log/apache2/error.log contains:
[mpm_prefork:notice] [pid 69090] AH00163: Apache/2.4.41 (Ubuntu)
OpenSSL/1.1.1k mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal
operations
[core:notice] [pid 69090] AH00094: Command line: '/usr/sbin/apache2'
I ran the usual shell commands to start a Django project:
root#localhost:~# django-admin.py startproject contact
and then I ran createsuperuser, collectstatic, etc., successfully.
I'm trying to use a Django form that is in /contact/contactform/templates/contact.html that contains this:
<form action="/contact/" method="post">
{% csrf_token %}
{{ form.as_p }}
<div class="frc-captcha mb-2" data-sitekey={{ captcha_site_key }}></div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
and going to https://example.com/contact/ throws a 403 error.
The .htaccess file at root has
RewriteEngine on
ServerSignature Off
Options All -Indexes
This is my public_html file structure:
/contact/contact/settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '...'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'contact.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'contact.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
/etc/apache2/sites-available/default-ssl.conf:
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
ServerAdmin webmaster#localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLEngine on
SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
#SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt
#SSLCACertificatePath /etc/ssl/certs/
#SSLCACertificateFile /etc/apache2/ssl.crt/ca-bundle.crt
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory /usr/lib/cgi-bin>
SSLOptions +StdEnvVars
</Directory>
Alias /static /var/www/html/example.com/public_html/contact/static
Alias /media /var/www/html/example.com/public_html/contact/media
<Directory /var/www/html/example.com/public_html/contact/static>
Require all granted
</Directory>
<Directory /var/www/html/example.com/public_html/contact/media>
Require all granted
</Directory>
WSGIScriptAlias /contact/contact /var/www/html/example.com/public_html/contact/contact/wsgi.py
WSGIDaemonProcess contact python-home=/var/www/html/example.com/public_html/contact/contact
WSGIProcessGroup contact
WSGISocketPrefix run/wsgi
<Directory /var/www/html/example.com/public_html/contact/contact>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
</VirtualHost>
</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
/contact/contact/wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'contact.settings')
application = get_wsgi_application()
/contact/contact/urls.py:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('contactform.urls', namespace='contactform')),
]
/contact/contactform/urls.py:
from django.urls import path
from . import views
app_name = 'contact'
urlpatterns = [
path('thanks/', views.thanks, name='thanks'),
path('contact/', views.contact, name='contact'),
]
One line of your 000-default.conf is defining the path to your python executable :
WSGIDaemonProcess contact python-path=/var/www/html/example.com/public_html/contact python-home=/var/www/html/example.com/public_html/contact/contact
If you want to let apache find the python used in the shell, you should remove the python-path argument
WSGIDaemonProcess contact python-home=/var/www/html/example.com/public_html/contact/contact
Or make it point to your python3 installation
WSGIDaemonProcess contact python-path=/my/python3/path python-home=/var/www/html/example.com/public_html/contact/contact
That way you will stop having a warning about python2.7 being used and it may help your project working
You should also ensure that your mod-wsgi was installed using python3 and not using python2.7
This is what finally worked for me:
I needed to add the #added lines in wsgi.py
(from https://www.metaltoad.com/blog/hosting-django-sites-apache )
import os
import sys #added
sys.path.append('/var/www/html/contact') #added
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'contact.settings')
application = get_wsgi_application()
And rather than edit /etc/apache2/sites-available/default-ssl.conf, I edited /etc/apache2/apache2.conf:
Alias /static /var/www/html/example.com/public_html/contact/static
Alias /media /var/www/html/example.com/public_html/contact/media
<Directory /var/www/html/example.com/public_html/contact/static>
Require all granted
</Directory>
<Directory /var/www/html/example.com/public_html/contact/media>
Require all granted
</Directory>
WSGIScriptAlias /contact /var/www/html/example.com/public_html/contact/contact/wsgi.py process-group=contact
WSGIDaemonProcess contact python-path=/var/www/html/example.com/public_html/contact
WSGIProcessGroup contact
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride all
Require all granted
<Files wsgi.py>
Require all granted
</Files>
</Directory>
I am trying to make a site with mvc structure. I have this :
www/
blog/
app/
admin/
controller/
model/
view/
config/
front/
controller/
model/
view/
assets/
images/
libs/
portfolio /
I have a first .htaccess at the root (www/) for Gzip compression and stuff.
I have a second .htaccess for my blog (in www/blog/) with my very basic redirection system :
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#QSA permet de garder les paramètres GET et les ajouter à la suite
RewriteRule (.*) index.php?p=$1 [QSA]
The file index.php in www/blog/ parses the url and uses the right controllers like this :
//****************************************************
include_once(APP_f.controller/controller.class.php');
$controlF = new ControleurF();
include_once(APP_b.'controleur/controleur.class.php');
$controlB = new ControleurB();
if (isset($_GET['p'])&&(substr($_GET['p'],0,4)== 'admin')) {
//on est dans l'admin
$lapage=explode('/',$_GET['p']);
if (!empty($lapage[1])) {$pp = $lapage[1];} else {$pp="index";}
if (!isset($pp) OR $pp == 'index')
{
$ctrl = "home"; $p = $ctrl;
} else {
$params = explode('/',$pp);
$ctrl = $params[0]; $p = $ctrl;
if (isset($params[1])) {
if ($params[1]<>"") {$p = $params[1];}
}
}
$c=$controlB->load($ctrl);
include_once($c);
}else{
//on est en front
if (!isset($_GET['p']) OR $_GET['p'] == 'index')
{
$ctrl = "home"; $p = $ctrl;
} else {
$params = explode('/',$_GET['p']);
$ctrl = $params[0]; $p = $ctrl;
if (isset($params[1])) {
if ($params[1]<>"") {$p = $params[1];}
}
}
$c=$controlF->load($ctrl);
include_once($c);
}
//****************************************************
Everything works fine but i am having trouble understanding how i could secure my admin folder with .htaccess/.htpasswd
Is there a way to do something like that in www/blog/.htaccess :
<Directory admin>
AuthUserFile "/home/foobar/www/blog/.htpasswd"
AuthGroupFile /dev/null
AuthName "Admin"
AuthType Basic
Require valid-user
</Directory>
The Directory directive can only be used in server configuration or virtual host files. It cannot be used in htaccess files. It is described in Apache Directory Directive.
To password protect a directory using htaccess, you have to enter the following in .htaccess file:
AuthType Basic
AuthName "Restricted Files"
# (Following line optional)
AuthBasicProvider file
AuthUserFile "/usr/local/apache/passwd/passwords"
Require user rbowen
The above commands will password protect the folder containing the htaccess file. The command: htpasswd -c /usr/local/apache/passwd/passwords rbowen generates a password for the user rbowen. It is described in Apache Authentication and Authorization
I find a way : use sessions with php
http://www.apprendre-php.com/tutoriels/tutoriel-14-les-sessions.html
Have a Vagrantbox with centos 7 and apache 2.4. In /var/www/html have a Codeigniter PHP Site with pretty-url rewrite. I create the vm with puphpet config.yaml. The VM is running correct, VM-server is running correct, mode_rewrite ist activ and allowed to all, but i try a url like this:
http://codeigniter.dev/home ->file not found
http://codeigniter.dev/index.php/home -> site ok
There is no way to replace index.php, don't know why?
On my Server with Centos and apache this configrution runs perfect, but in my VM it didn't replace?!?
Here are my Configs:
puphpet/config.yaml
vagrantfile:
target: local
vm:
provider:
local:
box: puphpet/centos7-x64
box_url: puphpet/centos7-x64
box_version: '0'
chosen_virtualizer: virtualbox
virtualizers:
virtualbox:
modifyvm:
natdnshostresolver1: false
showgui: 0
vmware:
numvcpus: 1
parallels:
linked_clone: 0
check_guest_tools: 0
update_guest_tools: 0
machines:
vflm_via243h8nsof:
id: codeigniter
hostname: codeigniter.dev.local
network:
private_network: 192.168.56.101
forwarded_port:
vflmnfp_57zntu84qm8k:
host: '9583'
guest: '22'
memory: '2048'
cpus: '1'
provision:
puppet:
manifests_path: puphpet/puppet/manifests
module_path:
- puphpet/puppet/modules
- puphpet/puppet/manifests
options:
- '--verbose'
- '--hiera_config /vagrant/puphpet/puppet/hiera.yaml'
synced_folder:
vflsf_f72ykqm374hd:
source: ./
target: /var/www
sync_type: default
smb:
smb_host: ''
smb_username: ''
smb_password: ''
mount_options:
dir_mode: '0775'
file_mode: '0664'
rsync:
args:
- '--verbose'
- '--archive'
- '-z'
exclude:
- .vagrant/
- .git/
auto: 'true'
owner: www-data
group: www-data
usable_port_range:
start: 10200
stop: 10500
post_up_message: ''
ssh:
host: 'false'
port: 'false'
private_key_path: 'false'
username: vagrant
guest_port: 'false'
keep_alive: '1'
forward_agent: 'false'
forward_x11: 'false'
shell: 'bash -l'
insert_key: 'false'
vagrant:
host: detect
proxy:
http: ''
https: ''
ftp: ''
no_proxy: ''
server:
install: '1'
packages: { }
users_groups:
install: '1'
groups:
- www-data
users:
- www-data
locale:
install: '1'
settings:
default_locale: de_DE.UTF-8
locales:
- en_GB.UTF-8
- en_US.UTF-8
timezone: Europe/Berlin
firewall:
install: '1'
rules: { }
cron:
install: '1'
jobs: { }
apache:
install: '1'
settings:
version: 2.4
user: www-data
group: www-data
default_vhost: true
manage_user: false
manage_group: false
sendfile: 0
modules:
- proxy_fcgi
- rewrite
vhosts:
av_myrx1sclhqnx:
servername: codeigniter.dev
serveraliases:
- www.codeigniter.dev
docroot: /var/www/html
port: '80'
setenv:
- 'APP_ENV dev'
setenvif:
- 'Authorization "(.*)" HTTP_AUTHORIZATION=$1'
custom_fragment: ''
ssl: '0'
ssl_cert: ''
ssl_key: ''
ssl_chain: ''
ssl_certs_dir: ''
ssl_protocol: ''
ssl_cipher: ''
directories:
avd_6sroj6oyuexi:
path: /var/www/html
options:
- Indexes
- FollowSymlinks
- MultiViews
allow_override:
- All
require:
- 'all granted'
custom_fragment: ''
files_match:
avdfm_o1gz78z6saqx:
path: \.php$
sethandler: 'proxy:fcgi://127.0.0.1:9000'
custom_fragment: ''
provider: filesmatch
provider: directory
letsencrypt:
install: '1'
settings:
email: admin#codeigniter.dev
domains: { }
php:
install: '1'
settings:
version: '7.1'
modules:
php:
- cli
- intl
- xml
pear: { }
pecl: { }
ini:
display_errors: 'On'
error_reporting: '-1'
session.save_path: /var/lib/php/session
date.timezone: UTC
fpm_ini:
error_log: /var/log/php-fpm.log
fpm_pools:
phpfp_jncm5era33zg:
ini:
prefix: www
listen: '127.0.0.1:9000'
security.limit_extensions: .php
user: www-user
group: www-data
composer: '1'
composer_home: ''
ruby:
install: '1'
versions:
rv_dpiw29f3bvhv:
default: '1'
bundler: '1'
version: 2.3.1
gems:
- deep_merge#1.0.1
- activesupport#4.2.6
- vine#0.2
python:
install: '1'
packages: { }
versions: { }
nodejs:
install: '1'
settings:
version: '6'
npm_packages: { }
mysql:
install: '1'
settings:
version: '5.7'
root_password: '123'
override_options: { }
adminer: 0
users:
mysqlnu_r5di0ad1ifk2:
name: dbuser
password: '123'
databases:
mysqlnd_k34jv21bgnjk:
name: codeigniter
sql: ''
grants:
mysqlng_rn6tn59qj8nf:
user: dbuser
table: '*.*'
privileges:
- ALL
.htaccess
RewriteEngine On
RewriteBase /
Options +FollowSymlinks
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
VM/ /etc/httpd/conf/httpd.conf
# Security
ServerTokens OS
ServerSignature On
TraceEnable On
ServerName "codeigniter.dev.local"
ServerRoot "/etc/httpd"
PidFile run/httpd.pid
Timeout 120
KeepAlive Off
MaxKeepAliveRequests 100
KeepAliveTimeout 15
LimitRequestFieldSize 8190
User www-data
Group www-data
<Directory /var/www/html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
</Directory>
HostnameLookups Off
ErrorLog "/var/log/httpd/error_log"
LogLevel warn
EnableSendfile Off
#Listen 80
Include "/etc/httpd/conf.modules.d/*.load"
Include "/etc/httpd/conf.modules.d/*.conf"
Include "/etc/httpd/conf/ports.conf"
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\"" forwarded
I read a lot of posting for this problem, but no solution, so i hope to get some help here.
I'm running MAMP 3.2.2 on Windows 10, with Apache on port 8888. I'm trying to password protect the directory C:\MAMP\htdocs\admin\ by placing a .htaccess and a .htpasswd files inside it.
.htacess is:
AuthType Basic
AuthName "Password Protected Area"
AuthUserFile C:\MAMP\htdocs\admin\.htpasswd
Require valid-user
.htpasswd (user = test; password = test) is:
test:dGRkPurkuWmW2
I checked MAMP's Apache httpd.conf and it says, in line 202:
<Directory />
Options FollowSymLinks ExecCGI
AllowOverride All
Order deny,allow
Allow from all
</Directory>
And, in line 220:
<Directory "C:\MAMP\htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks ExecCGI
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
When trying to navigate to "http://localhost:8888/admin/index.php" I get the "Authentication Required" dialog, saying that "http://localhost:8888 is requesting your username and password". But, after entering username and password, the dialog keeps reappearing, instead of granting me access.
What am I missing?
Thank you in advance!
The password test:dGRkPurkuWmW2 is wrong. Check the log files (\mamp\apache\logs\error.log) to see the error messages, there should be something like this:
[Sat Dec 10 10:39:04.965830 2016] [auth_basic:error] [pid 2200:tid 1648] [client ::1:49487] AH01617: user test: authentication failure for "/protected/": Password Mismatch
Use this HTPasswd Generator form to generate a valid password, which in your case for user test and password test will be something like this, but it always produces something different:
test:$apr1$2pi0lu5b$Omg8StTZWO0m5lMfq/D8d.
Here is a screen capture with my working example using the password above:
UPDATE
Note that this algorithm is working for Windows. The password you have at your code ($encryptedPassword = crypt($typedPassword, base64_encode($typedPassword));) works on Linux based systems and it is the default algorithm used by Apache 2.2.17 and older. From Apache 2.2.18, the default encryption method is based on MD5 and it can be used on both Windows and Linux based systems. You can read more about it here How to generate passwords for .htpasswd using PHP.
PHP code with the function crypt_apr1_md5 to generate a .htpasswd password entry for APR1-MD5 encryption compatible for windows:
<?php
// APR1-MD5 encryption method (windows compatible)
function crypt_apr1_md5($plainpasswd)
{
$salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8);
$len = strlen($plainpasswd);
$text = $plainpasswd.'$apr1$'.$salt;
$bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd));
for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $plainpasswd{0}; }
$bin = pack("H32", md5($text));
for($i = 0; $i < 1000; $i++)
{
$new = ($i & 1) ? $plainpasswd : $bin;
if ($i % 3) $new .= $salt;
if ($i % 7) $new .= $plainpasswd;
$new .= ($i & 1) ? $bin : $plainpasswd;
$bin = pack("H32", md5($new));
}
for ($i = 0; $i < 5; $i++)
{
$k = $i + 6;
$j = $i + 12;
if ($j == 16) $j = 5;
$tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
}
$tmp = chr(0).chr(0).$bin[11].$tmp;
$tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
return "$"."apr1"."$".$salt."$".$tmp;
}
// Password to be used for the user
$username = 'test';
$password = 'test';
// Encrypt password
$encrypted_password = crypt_apr1_md5($password);
// Print line to be added to .htpasswd file
echo $username . ':' . $encrypted_password;
I am using puppet to manage a varnish server with multiple backends. I am trying to create a loop so that additional backends can be added at a later date. So far I have the following in the erb file:
<% #backends.each do |backend| -%>
backend <%= backend['backend_name'] %> {
.host = "<%= #backend_addr %>";
.port = "<%= backend['backend_port'] %>";
.connect_timeout = 600s;
.first_byte_timeout = 600s;
.between_bytes_timeout = 600s;
}
<% end -%>
But when this is run I get the error:
Error: Could not retrieve catalog from remote server: Error 400 on SERVER: Failed to parse template varnish/drupal.vcl.erb:
Filepath: /etc/puppet/modules/varnish/templates/drupal.vcl.erb
Line: 17
Detail: no implicit conversion of String into Integer
at /etc/puppet/modules/varnish/manifests/init.pp:22 on node x.x.x.x
What am I doing wrong?