-
Notifications
You must be signed in to change notification settings - Fork 522
Expand file tree
/
Copy pathvirtualhost.sh
More file actions
executable file
·343 lines (267 loc) · 7.94 KB
/
Copy pathvirtualhost.sh
File metadata and controls
executable file
·343 lines (267 loc) · 7.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#!/usr/bin/env bash
set -Eeuo pipefail
# =========================
# BASE CONFIGURATION
# =========================
readonly EMAIL="webmaster@localhost"
readonly USER_DIR="/var/www"
readonly HOSTS_FILE="/etc/hosts"
readonly WSL_HOSTS_FILE="/mnt/c/Windows/System32/drivers/etc/hosts"
# =========================
# SYSTEM DETECTION
# =========================
get_distro_family() {
[[ -f /etc/os-release ]] || { echo "unknown"; return; }
. /etc/os-release
case "$ID" in
ubuntu|debian) echo "debian" ;;
centos|rhel|rocky|almalinux|fedora) echo "rhel" ;;
*)
[[ "${ID_LIKE:-}" == *debian* ]] && echo "debian" && return
[[ "${ID_LIKE:-}" == *rhel* ]] && echo "rhel" && return
echo "unknown"
;;
esac
}
is_wsl() {
grep -qi microsoft /proc/version 2>/dev/null && return 0
grep -qi microsoft /proc/sys/kernel/osrelease 2>/dev/null && return 0
return 1
}
# =========================
# UTILS
# =========================
die() {
printf "ERROR: %s\n" "$1" >&2
exit 1
}
info() {
printf "%s\n" "$1"
}
require_root() {
[[ "$(id -u)" -eq 0 ]] || die "Must be run as root (use sudo)"
}
detect_apache_user() {
local user
user=$(ps -eo user,comm | awk '/(apache2|httpd)/ && $1!="root" {print $1; exit}')
if [[ -n "$user" ]]; then
echo "$user"
elif [[ "$DISTRO_FAMILY" == "debian" ]]; then
echo "www-data"
else
echo "apache"
fi
}
sanitize_domain() {
local domain="$1"
[[ ${#domain} -le 253 ]] || die "Domain too long"
if [[ ! "$domain" =~ ^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$ ]]; then
die "Invalid domain name: $domain"
fi
}
is_root_domain() {
[[ "$(awk -F. '{print NF}' <<< "$1")" -eq 2 ]]
}
reload_apache() {
if [[ "$IS_WSL" == "true" ]]; then
apachectl -k graceful
else
systemctl reload "$APACHE_SERVICE"
fi
}
is_dir_empty() {
local dir="$1"
[[ -d "$dir" ]] || return 2
shopt -s nullglob dotglob
local files=("$dir"/*)
shopt -u nullglob dotglob
(( ${#files[@]} == 0 ))
}
enable_host() {
if [[ "$DISTRO_FAMILY" == "debian" ]]; then
# Activate rewrite module if not already enabled
# (required for canonical redirection)
if ! a2query -m rewrite >/dev/null 2>&1; then
a2enmod rewrite >/dev/null
fi
a2ensite "$DOMAIN" >/dev/null
fi
apachectl configtest || die "Apache configuration test failed"
}
disable_host() {
if [[ "$DISTRO_FAMILY" == "debian" ]]; then
a2dissite "$DOMAIN" >/dev/null
elif [[ "$DISTRO_FAMILY" == "rhel" ]]; then
rm -f "$SITES_ENABLED/$DOMAIN.conf"
fi
}
# =========================
# ENVIRONMENT SETUP BY DISTRO
# =========================
readonly DISTRO_FAMILY="$(get_distro_family)"
readonly IS_WSL="$(is_wsl && echo true || echo false)"
if [[ "$DISTRO_FAMILY" == "rhel" ]]; then
readonly APACHE_SERVICE="httpd"
readonly SITES_AVAILABLE="/etc/httpd/conf.d"
readonly SITES_ENABLED="/etc/httpd/conf.d"
elif [[ "$DISTRO_FAMILY" == "debian" ]]; then
readonly APACHE_SERVICE="apache2"
readonly SITES_AVAILABLE="/etc/apache2/sites-available"
readonly SITES_ENABLED="/etc/apache2/sites-enabled"
else
die "Unsupported Linux distribution. Only Debian-based and RHEL-based distros are supported."
fi
# =========================
# HOSTS MANAGEMENT
# =========================
add_host_entry() {
local domain="$1"
grep -q "[[:space:]]$domain\$" "$HOSTS_FILE" || \
echo "127.0.0.1 $domain" >> "$HOSTS_FILE"
if [[ "$IS_SUBDOMAIN" == "false" ]] && is_root_domain "$domain"; then
grep -q "[[:space:]]www.$domain\$" "$HOSTS_FILE" || \
echo "127.0.0.1 www.$domain" >> "$HOSTS_FILE"
fi
if [[ "$IS_WSL" == "true" && -w "$WSL_HOSTS_FILE" ]]; then
echo "127.0.0.1 $domain" >> "$WSL_HOSTS_FILE"
if [[ "$IS_SUBDOMAIN" == "false" ]] && is_root_domain "$domain"; then
echo "127.0.0.1 www.$domain" >> "$WSL_HOSTS_FILE"
fi
fi
}
remove_host_entry() {
local domain="$1"
sed -i "\|[[:space:]]$domain\$|d" "$HOSTS_FILE"
if [[ "$IS_SUBDOMAIN" == "false" ]] && is_root_domain "$domain"; then
sed -i "\|[[:space:]]www.$domain\$|d" "$HOSTS_FILE"
fi
if [[ "$IS_WSL" == "true" && -w "$WSL_HOSTS_FILE" ]]; then
sed -i "\|[[:space:]]$domain\$|d" "$WSL_HOSTS_FILE"
if [[ "$IS_SUBDOMAIN" == "false" ]] && is_root_domain "$domain"; then
sed -i "\|[[:space:]]www.$domain\$|d" "$WSL_HOSTS_FILE"
fi
fi
}
# =========================
# PARAMETERS & VALIDATION
# =========================
ACTION="${1:-}"
DOMAIN="${2:-}"
ROOT_DIR_INPUT="${3:-}"
IS_SUBDOMAIN="${4:-false}"
CANONICAL="${5:-root}"
# force domain name downcase
# for consistency
DOMAIN="${DOMAIN,,}"
require_root
[[ "$ACTION" == "create" || "$ACTION" == "delete" ]] || \
die "Use: $0 {create|delete} domain [root_dir] [is_subdomain] [canonical]"
while [[ -z "$DOMAIN" ]]; do
read -rp "Type domain: " DOMAIN
done
sanitize_domain "$DOMAIN"
case "$IS_SUBDOMAIN" in true|false) ;; *) die "is_subdomain must be true or false" ;; esac
case "$CANONICAL" in root|www) ;; *) die "canonical must be root or www" ;; esac
ROOT_DIR="${ROOT_DIR_INPUT:-${DOMAIN//./}}"
[[ "$ROOT_DIR" == /* ]] || ROOT_DIR="$USER_DIR/$ROOT_DIR"
readonly VHOST_FILE="$SITES_AVAILABLE/$DOMAIN.conf"
readonly APACHE_USER="$(detect_apache_user)"
# =========================
# CREATE
# =========================
create_vhost() {
[[ ! -f "$VHOST_FILE" ]] || die "Domain already exists"
if [[ ! -d "$ROOT_DIR" ]]; then
mkdir -p "$ROOT_DIR"
chmod 755 "$ROOT_DIR"
fi
if [[is_dir_empty "$ROOT_DIR" ]]; then
cat > "$ROOT_DIR/index.html" <<EOF
<html><body><h1>Welcome to $DOMAIN</h1></body></html>
EOF
cat > "$ROOT_DIR/phpinfo.php" <<EOF
<?php phpinfo(); ?>
EOF
fi
# Canonical domain
CANONICAL_DOMAIN="$DOMAIN"
if [[ "$IS_SUBDOMAIN" == "false" ]] && is_root_domain "$DOMAIN" && [[ "$CANONICAL" == "www" ]]; then
CANONICAL_DOMAIN="www.$DOMAIN"
fi
cat > "$VHOST_FILE" <<EOF
# === METADATA ===
# is_subdomain=$IS_SUBDOMAIN
# canonical=$CANONICAL
# root_dir=$ROOT_DIR
# === /METADATA ===
<VirtualHost *:80>
ServerAdmin $EMAIL
ServerName $CANONICAL_DOMAIN
EOF
if [[ "$IS_SUBDOMAIN" == "false" ]] && is_root_domain "$DOMAIN"; then
if [[ "$CANONICAL" == "www" ]]; then
echo " ServerAlias $DOMAIN" >> "$VHOST_FILE"
else
echo " ServerAlias www.$DOMAIN" >> "$VHOST_FILE"
fi
fi
cat >> "$VHOST_FILE" <<EOF
DocumentRoot $ROOT_DIR
<Directory $ROOT_DIR>
AllowOverride All
Require all granted
</Directory>
RewriteEngine On
EOF
if [[ "$IS_SUBDOMAIN" == "false" ]] && is_root_domain "$DOMAIN"; then
if [[ "$CANONICAL" == "www" ]]; then
cat >> "$VHOST_FILE" <<EOF
RewriteCond %{HTTP_HOST} ^$DOMAIN\$ [NC]
RewriteRule ^(.*)$ http://www.$DOMAIN/\$1 [R=301,L]
EOF
else
cat >> "$VHOST_FILE" <<EOF
RewriteCond %{HTTP_HOST} ^www\\.$DOMAIN\$ [NC]
RewriteRule ^(.*)$ http://$DOMAIN/\$1 [R=301,L]
EOF
fi
fi
cat >> "$VHOST_FILE" <<EOF
ErrorLog \${APACHE_LOG_DIR}/${DOMAIN}-error.log
CustomLog \${APACHE_LOG_DIR}/${DOMAIN}-access.log combined
</VirtualHost>
EOF
add_host_entry "$DOMAIN"
chown -R "${APACHE_USER:-www-data}:${APACHE_USER:-www-data}" "$ROOT_DIR" 2>/dev/null || true
enable_host
reload_apache
info "VirtualHost created: http://$CANONICAL_DOMAIN"
}
# =========================
# DELETE
# =========================
load_metadata() {
IS_SUBDOMAIN="$(grep -oP '(?<=is_subdomain=).*' "$VHOST_FILE" || echo false)"
CANONICAL="$(grep -oP '(?<=canonical=).*' "$VHOST_FILE" || echo root)"
ROOT_DIR="$(grep -oP '(?<=root_dir=).*' "$VHOST_FILE" || echo "")"
}
delete_vhost() {
[[ -f "$VHOST_FILE" ]] || die "The specified domain does not exist."
load_metadata
remove_host_entry "$DOMAIN"
disable_host
reload_apache
rm -f "$VHOST_FILE"
if [[ -d "$ROOT_DIR" ]]; then
read -rp "Delete directory $ROOT_DIR? (y/N): " confirm
[[ "$confirm" =~ ^[Yy]$ ]] && rm -rf "$ROOT_DIR"
fi
info "VirtualHost deleted: $DOMAIN"
}
# =========================
# MAIN
# =========================
case "$ACTION" in
create) create_vhost ;;
delete) delete_vhost ;;
esac