-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerBuilding
More file actions
1836 lines (1618 loc) · 62.7 KB
/
Copy pathServerBuilding
File metadata and controls
1836 lines (1618 loc) · 62.7 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# This script builds and settings a server.
set -o errexit # Exit on most errors (see the manual)
set -o errtrace # Make sure any error trap is inherited
set -o nounset # Disallow expansion of unset variables
set -o pipefail # Use last non-zero exit code in a pipeline
# Global Variables
#
declare -A _VAR
_VAR[Environment]="$(hostnamectl | grep Chassis | awk '{print $2}')"
_VAR[Hostname]="$HOSTNAME"
_VAR[IP]="$(hostname -I | awk '{print $2}')"
_VAR[Firewall]="$(LANG=C sudo ufw status 2>/dev/null | grep Status: | cut -d ' ' -f 2)"
_VAR[CPUs]="$(grep -c ^processor /proc/cpuinfo)" # number of CPUs/cores
_VAR[Timezone]="$(timedatectl | grep -e 'Time zone' | tr -s " " | cut -d ' ' -f 4)"
_VAR[Distribution]="$(cat /etc/*-release 2>/dev/null | grep DISTRIB_ID | cut -d= -f2)"
_VAR['Distro Codename']="$(cat /etc/*-release 2>/dev/null | grep DISTRIB_CODENAME | cut -d= -f2)"
_VAR['Distro Ubuntu Codename']="$(cat /etc/*-release 2>/dev/null | grep UBUNTU_CODENAME | cut -d= -f2)"
_VAR['Version Kernel']="$(uname -r)"
_VAR['Free/total memory']="$(free -m | xargs | awk '{print $10 " / " $8 " MB"}')"
_VAR['Free/total disk']="$(df -h | xargs | awk '{print $11 " / " $9}')"
# Packages Versions
# Nginx Ver
ver="$(apt-cache policy nginx-full | grep Candidate| cut -d' ' -f 4)"
_VER_NGINX_CAN="${ver:0:4}"
if [ "$(apt-cache policy nginx-full | grep Installed | cut -d' ' -f 4)" == "(none)" ]; then
_VER_NGINX_INS="(none)"
else
ver="$(apt-cache policy nginx-full | grep Installed | cut -d' ' -f 4)"
_VER_NGINX_INS="${ver:0:4}"
fi
_VAR['Version Nginx']="${_VER_NGINX_INS} / ${_VER_NGINX_CAN}"
# MySQL Ver
ver="$(apt-cache policy mysql-server | grep Candidate| cut -d' ' -f 4)"
_VER_MYSQL_CAN="${ver:0:3}"
if [ "$(apt-cache policy mysql-server | grep Installed | cut -d' ' -f 4)" == "(none)" ]; then
_VER_MYSQL_INS="(none)"
else
ver="$(apt-cache policy mysql-server | grep Installed | cut -d' ' -f 4)"
_VER_MYSQL_INS="${ver:0:3}"
fi
_VAR['Version MySQL']="${_VER_MYSQL_INS} / ${_VER_MYSQL_CAN}"
# PHP Ver
ver="$(apt-cache policy php-fpm | grep Candidate| cut -d':' -f 3)"
_VER_PHPFPM_CAN="${ver:0:3}"
if [ "$(apt-cache policy php-fpm | grep Installed | cut -d' ' -f 4)" == "(none)" ]; then
_VER_PHPFPM_INS="(none)"
else
ver="$(apt-cache policy php-fpm | grep Installed | cut -d':' -f 3)"
_VER_PHPFPM_INS="${ver:0:3}"
fi
_VAR['Version PHP-FPM']="${_VER_PHPFPM_INS} / ${_VER_PHPFPM_CAN}"
_VERSION_SCRIPT="1.0"
_USER_WEB="www-data"
_PATH_LETSENCRYPT_WEBROOT="/var/www/_letsencrypt/"
_PATH_LETSENCRYPT_CERTIFICATE="/etc/letsencrypt/live/"
_PATH_CERTIFICATES_IMPORT="/vagrant/Self-Signed Sertificates/" # only use in local virtualhost
_PATH_ODOO_ADDONS="/opt/odoo/addons,/opt/odoo/addons_custom"
usage(){
echo "
This script builds and settings a server.
Usage: $(basename "${0}") [option] [arguments]
-l Update and clean the system.
-e, --nginx Install Nginx server.
--nginx-conf Config Nginx server (update all config files).
-b, --nginx-block <domain> Create and modify a Nginx server block.
--subdomain <subdoman> Set subdomain (<subdoman>.example.com).
-r, --redirect <https|sub> Force SSL redirect.
(http://example.com >>> https://example.com)
Redirect subdomains.
(*.example.com >>> example.com)
-s, --ssl <domain> Create an SSL certificate for domain.
-p, --path <custompath> Set custom webrot path in /vat/www/<custompath>
(default: /var/www/<domain>/public)
-m, --mysql Install MySQL server.
--mysql-add-user Add MySQL user.
-p, --php Install PHP-FPM.
--php-admin Install and config PhpMyAdmin.
-w, --wp <path> Install WordPress (whit WP-CLI).
Install and activate a plugin/theme
from WP plugin directory.
--wp-plugin <path> <plugins>
--wp-theme <path> <plugins>
--wp-update Update WordPres.
-o, --odoo Build the Odoo server from source.
-i, --info Display system info.
--log <domain> Show Nginx acces and error log in real-time.
Whach default logs use '--log default' argument.
-t, --timezone Set system timezone.
-g, --geoip Install and update GeoIP2 database (MaxMind).
-v, --version Display script version number.
-h, --help Display this help message.
"
exit 2
}
# Helper-function: check a package exists
packages_exists() {
if [ $# -gt 1 ]; then
echo " Error: Too many arguments in ${FUNCNAME[0]}() function in line: $LINENO"
exit 1
fi
local _PACKAGE=${1}
if type -P ${_PACKAGE} &>/dev/null; then
return 0
else
echo "
Dependency Warning:
The '${_PACKAGE}' is not installed on your system,
please install it and then run the script again.
"; exit 0
fi
}
info() {
printf "\nSystem Info (%s):\n" "$(date)"
echo "--------------------------------------------------"
local _BORDER="--------------------------------------------------"
_BORDER=$_BORDER$_BORDER
local _HEADER=" %-25s %-15s\n"
local _CONTENT=" %-25s %-15s\n"
printf "$_HEADER" "NAME" "VALUE"
printf "%50.50s\n" "$_BORDER"
for _NAME in "${!_VAR[@]}"; do
[[ -z "${_VAR[$_NAME]}" ]] && _VAR[$_NAME]="n/a"
printf "$_CONTENT" "$_NAME" "${_VAR[$_NAME]}"
done | sort -n
printf "%50.50s\n" "$_BORDER"
echo -e "* Version: installed / candidate\n"
}
show_log() {
# Display the last 3 lines of log (acces and error) files in real-time
# if [[ ! -f "/var/log/nginx/${_DOMAIN:-}access.log" ]]; then
# echo -e " Error: the file does not exist in the specified location:\n /var/log/nginx/${_DOMAIN:-}.access.log " >&2
# exit 1
# fi
if [[ "${_DOMAIN:-}" == "default" ]]; then
watch tail -n 3 /var/log/nginx/access.log /var/log/nginx/error.log
else
watch tail -n 3 /var/log/nginx/${_DOMAIN:-}.access.log /var/log/nginx/${_DOMAIN:-}.error.log
fi
}
linux(){
# Upgrading packages if necessary
sudo apt update
echo ""
if [[ $(LANG=C apt-get upgrade -s | grep -P '^\d+ upgraded'| cut -d" " -f1) != 0 ]]; then
sudo apt upgrade -y
fi
# System cleaning
#
# Remove leftover config files
if [[ -z "$(COLUMNS= dpkg -l | grep '^rc' | tr -s ' ' | cut -d ' ' -f 2)" ]]; then
echo " There aren't leftover config files."
else
echo "Remove leftover config files:"
sudo dpkg --purge $(COLUMNS= dpkg -l | grep '^rc' | tr -s ' ' | cut -d ' ' -f 2)
fi
# Clean packages cache
sudo apt clean
# Remove orphaned packages
if [[ $(LANG=C apt-get autoremove -s | grep -P '^\d+ upgraded'| cut -d" " -f6) -ne 0 ]]; then
sudo apt autoremove -y -qq
fi
# Flush the cache of Linux memory
# sudo /sbin/sysctl vm.drop_caches=3
# UFW enable
sudo ufw default deny incoming &>/dev/null
sudo ufw default allow outgoing &>/dev/null
sudo ufw allow ssh comment 'SSH' &>/dev/null && printf " Ufw rule: allow SSH\n"
if [[ "${_VAR[Firewall]}" != "active" ]]; then
sudo ufw --force enable
fi
sudo ufw reload &>/dev/null && echo " ✔ Firewall reloaded"
}
timezone() {
_TIMEZONE="$(timedatectl | grep -e 'Time zone' | tr -s " " | cut -d ' ' -f 4)"
# if [[ "${_TIMEZONE}" == "Etc/UTC" ]] || [[ "${_TIMEZONE}" == "" ]]; then
echo "Current timezone on system: ${_TIMEZONE}"
read -p "Do you want to set a new timezone? [y/n] " REPLY
if [[ "${REPLY:-}" =~ ^[Yy]$ ]]; then
read -p "Enter the new time zone (format: Continent/City): " _SET_TIMEZONE
if [[ $(timedatectl list-timezones | grep "${_SET_TIMEZONE}" &> /dev/null; echo $?) != "0" ]]; then
echo " Error: '${_SET_TIMEZONE}' invalid timezone. Try again..." && exit 1
else
sudo timedatectl set-timezone "${_SET_TIMEZONE}" && echo "Done."
_TIMEZONE="${_SET_TIMEZONE}"
fi
fi
# fi
}
geoip() {
if ! which geoipupdate &>/dev/null; then
# Install GeoIP2 database
read -p "Do you want to install/update the GeoIP database? [y/n] " REPLY
if [[ "${REPLY:-}" =~ ^[Yy]$ ]]; then
echo "
NOTE: You will need an MaxMind Account ID and License Key.
For more information about this, visit the docs at
https://dev.maxmind.com/geoip/geoipupdate/
"
read -p "Do you have an account ID for MaxMind, ... (select 'no' to skip the database installation)? [y/n] " REPLY
if [[ "${REPLY:-}" =~ ^[Yy]$ ]]; then
read -p " Enter your AccountID: " _MAXMIND_ACCOUNTID
read -p " Enter your LicenseKey: " _MAXMIND_LICENSEKEY
sudo apt install -y geoipupdate
sudo sed -i "s/AccountID.*/AccountID ${_MAXMIND_ACCOUNTID}/g" /etc/GeoIP.conf
sudo sed -i "s/LicenseKey.*/LicenseKey ${_MAXMIND_LICENSEKEY}/g" /etc/GeoIP.conf
sudo geoipupdate -d /usr/share/GeoIP/ && echo " ✔ GeoIP database installed"
fi
fi
else
# Update GeoIP2 database
if [ ! -f "/usr/share/GeoIP/.geoipupdate.lock" ]; then
sudo geoipupdate -d /usr/share/GeoIP/ && echo " ✔ GeoIP database updated"
else
echo " ✔ GeoIP database is up to date"
fi
fi
}
domain_validate(){
# Domain validate (simple)
if [[ $(echo ${_DOMAIN:-} | grep -P "^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$"; echo $?) == 1 ]] && [ "${_DOMAIN:-}" != "default" ]; then
echo -e "\n Info: The '${_DOMAIN:-}' is not a valid domain name."
read -p " Do you want to continue? [y/n] " REPLY
echo ""
if [[ "${REPLY:-}" =~ ^[Nn]$ ]]; then
exit 0
fi
fi
}
ssl_certificate() {
if [ "${_DOMAIN}" == "default" ]; then
_DOMAIN=${_VAR[Hostname]}
fi
##
# Self-signed certificate in local environment
##
if [[ "${_VAR[Environment]}" == "vm" ]]; then
if [ ! -f "${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/fullchain.pem" ]; then
sudo mkdir -p ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}
sudo cp -rf /etc/ssl/openssl.cnf /tmp/openssl.${_DOMAIN:-}.cnf
sudo sed -i "1i SAN=\"email:info@${_DOMAIN:-}\"" /tmp/openssl.${_DOMAIN:-}.cnf
if [[ "${_DOMAIN:-}" == "${_VAR[Hostname]}" ]]; then
# Create a certificate for default host
# Example, if hostname equal 'VPS':
# -b VPS Default host available at https://${_VAR[IP]}
# after you imported the VPS.crt. file(s) to the Chrome web browser
sudo sed -i "s/^# Extensions for a typical CA/subjectAltName=IP:${_VAR[IP]}/g" /tmp/openssl.${_DOMAIN:-}.cnf
else
sudo sed -i "s/^# Extensions for a typical CA/subjectAltName=DNS:${_DOMAIN:-}, DNS:www.${_DOMAIN:-}, DNS:*.${_DOMAIN:-}/g" /tmp/openssl.${_DOMAIN:-}.cnf
fi
# Create certificates
sudo openssl req \
-x509 -new -sha256 -days 365 -nodes -newkey rsa:2048 \
-subj "/C=US/ST=New York/L=New York/O=123 SSL - Local Tester/OU=IT/CN=${_DOMAIN:-}" \
-out ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/fullchain.pem \
-keyout ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/privkey.pem \
-config /tmp/openssl.${_DOMAIN:-}.cnf > /dev/null 2>&1 || echo " Error: creating self-signed certificate -- '${_DOMAIN:-}'"
# Fixing cURL SSL connection issue
cat "${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/fullchain.pem" | sudo tee /usr/share/ca-certificates/${_DOMAIN:-}.crt > /dev/null
sudo bash -c "cat >> /etc/ca-certificates.conf" <<CERT
# Fixing cURL SSL connection issue
${_DOMAIN:-}.crt
CERT
sudo update-ca-certificates --fresh > /dev/null
fi
# Import to web browsers (vagrant-triggers or manual import)
mkdir -p "${_PATH_CERTIFICATES_IMPORT}"
cat "${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/fullchain.pem" | sudo tee "${_PATH_CERTIFICATES_IMPORT}/${_DOMAIN:-}.crt" > /dev/null && echo " ✔ SSL cert for '${_DOMAIN:-}' is ready (import into the Chrome browser)"
else
##
# Let's Encrypt certificate in production environment
##
packages_exists "certbot"
if [[ $(sudo certbot certificates 2>/dev/null | grep --quiet www.${_DOMAIN:-}; echo $?) != 0 ]]; then
echo "You need a valid e-mail address for obtaining SSL"
echo "certificates from Let's Encrypt using Certbot!"
read -p "Enter e-mail adress:" _CERT_EMAIL
echo ""
# Diasable SSL config
sudo sed -i -r 's/(listen .*443)/\1;#/g; s/(ssl_(certificate|certificate_key|trusted_certificate) )/#;#\1/g' /etc/nginx/conf.d/${_DOMAIN:-}.conf
# Run certbot (https://certbot.eff.org/docs/using.html)
# Use certbot --dry-run flag to test
sudo certbot --nginx certonly --agree-tos --no-eff-email --email ${_CERT_EMAIL} -d ${_DOMAIN} -d www.${_DOMAIN} -d cdn.${_DOMAIN} -d doc.${_DOMAIN} -d shop.${_DOMAIN} forum.${_DOMAIN} api.${_DOMAIN} blog.${_DOMAIN} help.${_DOMAIN} info.${_DOMAIN} dev.${_DOMAIN} || _error "creating Let’s Encrypt certificate -- '${_DOMAIN}'"
# Re-enable SSL config
sudo sed -i -r 's/#?;#//g' /etc/nginx/conf.d/${_DOMAIN:-}.conf
fi
# Expand certbot with subdomain (You can use wildcard certificate too, more info at https://certbot.eff.org/docs/using.html#dns-plugins)
if [[ -n "${_SUB}" ]]; then
if [[ $(sudo certbot certificates 2>/dev/null | grep --quiet ${_SUB}${_DOMAIN}; echo $?) != 0 ]]; then
sudo certbot --nginx certonly --expand --agree-tos --no-eff-email -d ${_DOMAIN} -d www.${_DOMAIN} -d ${_SUB}${_DOMAIN} || _error "creating Let’s Encrypt certificate -- '${_SUB}${_DOMAIN}'"
fi
fi
fi
}
nginx(){
if which nginx &>/dev/null; then
echo " ✔ The Nginx server is already installed"
else
sudo apt update
timezone
sudo apt install nginx-full -y
# Enable the Nginx server starting after a reboot
sudo systemctl enable nginx &>/dev/null
# Allow UFW for Nginx
sudo ufw allow 'Nginx Full' comment 'server' &>/dev/null && echo " Ufw rule: allow Nginx Full"
echo " ✔ The Nginx server is installed"
nginx_config
_DOMAIN="default"
nginx_block
fi
}
nginx_config() {
packages_exists "nginx"
if ! which certbot &>/dev/null; then
sudo apt -y install certbot python3-certbot-nginx
# Notes: The 'ssl-dhparams.pem' file will be created after installing and run certbot.
sudo certbot --dry-run renew # there is nothing renewable yet
fi
sudo systemctl enable certbot.timer
# Add a Diffie-Hellman parameter
# if [ ! -f "/etc/letsencrypt/ssl-dhparams.pem" ]; then
# sudo mkdir -p /etc/letsencrypt/
# echo "
# Generating DH parameters...
# - Only need to be generated once if it is not exists!
# - This is going to take a few (10-15) minutes.
# "
# # Generate a Diffie-Hellman parameter
# sudo openssl genpkey -genparam -algorithm DH -out /etc/letsencrypt/ssl-dhparams.pem -pkeyopt dh_paramgen_prime_len:4096 > /dev/null 2>&1
# fi
sudo bash -c "cat > /etc/nginx/nginx.conf" << NGINXCONFIG
##
# Nginx Config
##
user ${_USER_WEB};
pid /run/nginx.pid;
worker_processes auto;
worker_rlimit_nofile 65535;
include /etc/nginx/modules-enabled/*.conf;
events {
multi_accept on;
worker_connections 65535;
}
http {
charset utf-8;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
server_tokens off;
log_not_found off;
types_hash_max_size 2048;
client_max_body_size 16M;
# MIME
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging
log_format custom '[\$time_local] \$remote_addr \$remote_user '
'"\$request" \$status \$body_bytes_sent '
'"\$http_referer" "\$http_user_agent" '
'"\$http_x_forwarded_for" \$request_id '
'\$geoip_country_name \$geoip_country_code '
'\$geoip_region_name \$geoip_city ';
access_log /var/log/nginx/access.log custom;
error_log /var/log/nginx/error.log warn;
# Limits
limit_req_log_level warn;
limit_req_zone \$binary_remote_addr zone=login:10m rate=10r/m;
# SSL
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
NGINXCONFIG
if [ -f "/etc/letsencrypt/ssl-dhparams.pem" ]; then
sudo bash -c "cat >> /etc/nginx/nginx.conf" << NGINXCONFIG
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
NGINXCONFIG
fi
sudo bash -c "cat >> /etc/nginx/nginx.conf" << NGINXCONFIG
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
NGINXCONFIG
if [[ "${_VAR[Environment]}" != "vm" ]]; then
sudo bash -c "cat >> /etc/nginx/nginx.conf" << NGINXCONFIG
ssl_stapling on;
ssl_stapling_verify on;
resolver 1.1.1.1 1.0.0.1 8.8.8.8 8.8.4.4 208.67.222.222 208.67.220.220 valid=60s;
resolver_timeout 2s;
NGINXCONFIG
fi
if [ -f "/usr/share/GeoIP/GeoLite2-Country.mmdb" ]; then
sudo bash -c "cat >> /etc/nginx/nginx.conf" <<NGINXCONFIG
# GeoIP Database
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
auto_reload 60m;
\$geoip2_data_country_code country iso_code;
\$geoip2_data_country_name country names en;
}
geoip2 /usr/share/GeoIP/GeoLite2-City.mmdb {
auto_reload 60m;
\$geoip2_metadata_city_build metadata build_epoch;
\$geoip2_data_city_name city names en;
}
# Block countries
# map $geoip2_data_country_code \$domain_allowed_country {
# default yes;
# RU no;
# }
# You need to determine in the server block configuration
# what to do if the country is not allowed...
# Example:
# location / {
# if (\$domain_allowed_country = no) {
# return 444;
# }
# }
NGINXCONFIG
fi
sudo bash -c "cat >> /etc/nginx/nginx.conf" << NGINXCONFIG
# Virtual Host Configs
include /etc/nginx/conf.d/*.conf;
}
NGINXCONFIG
sudo bash -c "cat > /etc/nginx/snippets/letsencrypt.conf" <<NGINXLETSENCRYPT
##
# ACME-challenge
##
location ^~ /.well-known/acme-challenge/ {
root ${_PATH_LETSENCRYPT_WEBROOT};
}
NGINXLETSENCRYPT
sudo bash -c "cat > /etc/nginx/snippets/general.conf" <<NGINXGENERAL
##
# General Config
##
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
log_not_found off;
access_log off;
}
# Cache-Control - Expiration
location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)\$ {
expires 365d;
access_log off;
}
location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff2?)\$ {
add_header Access-Control-Allow-Origin "*";
expires 365d;
access_log off;
}
# Gzip
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
NGINXGENERAL
sudo bash -c "cat > /etc/nginx/snippets/fastcgi-php.conf" <<FASTCGICONFIG
##
# PHP FastCGI config
##
# 404
try_files \$fastcgi_script_name =404;
# default fastcgi_params
include /etc/nginx/fastcgi_params;
# fastcgi settings
fastcgi_pass unix:/var/run/php/php-fpm.sock;
fastcgi_index index.php;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
# fastcgi params
fastcgi_param DOCUMENT_ROOT \$realpath_root;
fastcgi_param SCRIPT_FILENAME \$realpath_root\$fastcgi_script_name;
fastcgi_param PHP_ADMIN_VALUE "open_basedir=\$base/:/usr/lib/php/:/tmp/:/usr/share/phpmyadmin/";
FASTCGICONFIG
# If GeoIP database exists add this below to php-fastcgi.conf
if [ -f "/usr/share/GeoIP/GeoLite2-Country.mmdb" ]; then
sudo bash -c "cat >> /etc/nginx/snippets/fastcgi-php.conf" <<FASTCGICONFIG
fastcgi_param COUNTRY_CODE \$geoip2_data_country_code;
fastcgi_param COUNTRY_NAME \$geoip2_data_country_name;
fastcgi_param CITY_NAME \$geoip2_data_city_name;
FASTCGICONFIG
fi
sudo bash -c "cat > /etc/nginx/snippets/proxy.conf" <<PROXYCONFIG
##
# Proxy Config (proxy_params)
##
proxy_http_version 1.1;
proxy_cache_bypass \$http_upgrade;
# Proxy headers
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_set_header X-Forwarded-Host \$host;
proxy_set_header X-Forwarded-Port \$server_port;
# Proxy timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
PROXYCONFIG
sudo bash -c "cat > /etc/nginx/snippets/security.conf" <<NGINXSECURITY
##
# Security Config
##
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
# add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header "X-UA-Compatible" "IE=Edge";
location ~ /\.(?!well-known) {
deny all;
}
NGINXSECURITY
sudo bash -c "cat > /etc/nginx/snippets/phpmyadmin.conf" <<NGINXPHPADMIN
##
# PhpMyAdmin Config
##
location /phpmyadmin {
root /usr/share/;
location ~ ^/phpmyadmin/(doc|sql|setup|libraries|templates)/ {
return 404;
}
location ~ ^/phpmyadmin/(.+\.php)\$ {
include /etc/nginx/snippets/fastcgi-php.conf;
}
location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))\$ {
root /usr/share/;
}
}
NGINXPHPADMIN
sudo bash -c "cat > /etc/nginx/snippets/wordpress.conf" <<WORDPRESSCONFIG
##
# WordPress config
##
# Redirect 403 HTTP status return code to 404
error_page 403 =404 /404;
# WordPress: allow TinyMCE
# location = /wp-includes/js/tinymce/wp-tinymce.php {
# include /etc/nginx/snippets/fastcgi-php.conf;
# }
# WordPress: deny wp-content, wp-includes php files
location ~* ^/(?:wp-content|wp-includes)/.*\.php\$ {
deny all;
}
# WordPress: deny wp-content/uploads nasty stuff
location ~* ^/wp-content/uploads/.*\.(?:s?html?|php|js|swf)\$ {
deny all;
}
# WordPress: SEO plugin
location ~* ^/wp-content/plugins/wordpress-seo(?:-premium)?/css/main-sitemap\.xsl\$ {}
# WordPress: deny wp-content/plugins (except earlier rules)
location ~ ^/wp-content/plugins {
deny all;
}
# WordPress: deny scripts and styles concat
# location ~* \/wp-admin\/load-(?:scripts|styles)\.php {
# deny all;
# }
# WordPress: deny general stuff
location ~* ^/(?:xmlrpc\.php|wp-links-opml\.php|wp-config\.php|wp-config-sample\.php|wp-comments-post\.php|readme\.html|license\.txt|olvasdel\.html|licenc\.txt)\$ {
deny all;
}
# WordPress: throttle wp-login.php
location = /wp-login.php {
limit_req zone=login burst=2 nodelay;
include /etc/nginx/snippets/fastcgi-php.conf;
}
WORDPRESSCONFIG
sudo nginx -s reload && echo " ✔ Nginx Server setting and reloading is OK"
}
nginx_block(){
domain_validate
ssl_certificate
if [[ "${_DOMAIN:-}" == "${_VAR[Hostname]}" ]]; then
_DOMAIN="default"
fi
sudo rm -rf /etc/nginx/{sites-enabled/default,sites-available/default}
if [[ "${_DOMAIN:-}" == "default" ]]; then
sudo bash -c "cat > /etc/nginx/conf.d/default.conf" << DEFAULTBLOCK
server {
listen 80 default_server;
listen [::]:80 default_server;
DEFAULTBLOCK
if [ -f "${_PATH_LETSENCRYPT_CERTIFICATE}${_VAR[Hostname]}/fullchain.pem" ]; then
sudo bash -c "cat >> /etc/nginx/conf.d/default.conf" << DEFAULTBLOCK
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
ssl_certificate ${_PATH_LETSENCRYPT_CERTIFICATE}${_VAR[Hostname]}/fullchain.pem;
ssl_certificate_key ${_PATH_LETSENCRYPT_CERTIFICATE}${_VAR[Hostname]}/privkey.pem;
DEFAULTBLOCK
fi
sudo bash -c "cat >> /etc/nginx/conf.d/default.conf" << DEFAULTBLOCK
set \$base /var/www/html;
root \$base;
index index.php index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files \$uri \$uri/ =404;
}
DEFAULTBLOCK
if [ -d "/usr/share/phpmyadmin" ]; then
sudo bash -c "cat >> /etc/nginx/conf.d/default.conf" << DEFAULTBLOCK
include /etc/nginx/snippets/phpmyadmin.conf;
DEFAULTBLOCK
fi
if [[ "${_VAR[Environment]}" != "vm" ]]; then
sudo bash -c "cat >> /etc/nginx/conf.d/default.conf" << DEFAULTBLOCK
##
# CONNECTION CLOSED WITHOUT RESPONSE
##
return 444;
DEFAULTBLOCK
fi
sudo bash -c "cat >> /etc/nginx/conf.d/default.conf" << DEFAULTBLOCK
}
DEFAULTBLOCK
else
##
# Creating a block for VHOST
##
# Set server paths
if [[ -n "${_SUB:-}" ]]; then
_SUB="${_SUB:-}."
fi
if [[ -n "${_PATH_WEBROOT_CUSTOM:-}" ]]; then
_PATH_WEBROOT="/var/www/${_PATH_WEBROOT_CUSTOM:-}"
_PATH_WEBROOT=${_PATH_WEBROOT//\/\///} # remove a double backslash
else
_PATH_WEBROOT="/var/www/${_SUB:-}${_DOMAIN:-}/public"
fi
echo -e "\nCreating or updating a Nginx server block : "
echo "------------------------------------------------"
echo " Domain: ${_SUB:-}${_DOMAIN:-}"
echo " Webrot: ${_PATH_WEBROOT}"
echo " Redirect https: ${_REDIRECT_HTTPS:-false}"
echo " Redirect subdomain: ${_REDIRECT_SUB:-false}"
echo ""
read -p "Are you sure? [y/n] " REPLY
[[ ! "${REPLY:-}" =~ ^[Yy]$ ]] && exit
# Create server path
sudo mkdir -p {${_PATH_WEBROOT:-},${_PATH_LETSENCRYPT_WEBROOT}}
# Set FQDN
_FQDN="${_VAR[IP]} ${_VAR[Hostname]}.${_DOMAIN:-} ${_VAR[Hostname]} ${_DOMAIN:-}"
grep "${_FQDN}" /etc/hosts &>/dev/null || printf "%s\n" "${_FQDN}" | sudo tee -a /etc/hosts > /dev/null
sudo bash -c "cat > /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
server {
VHOSTBLOCK
if ! ${_REDIRECT_HTTPS:-false}; then
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
listen 80;
listen [::]:80;
VHOSTBLOCK
fi
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name ${_DOMAIN:-};
root ${_PATH_WEBROOT:-};
# SSL
ssl_certificate ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/fullchain.pem;
ssl_certificate_key ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/privkey.pem;
VHOSTBLOCK
if [[ "${_VAR[Environment]}" != "vm" ]]; then
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
ssl_trusted_certificate ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/chain.pem;
VHOSTBLOCK
fi
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
# security
include /etc/nginx/snippets/security.conf;
# logging
access_log /var/log/nginx/${_DOMAIN:-}.access.log;
error_log /var/log/nginx/${_DOMAIN:-}.error.log warn;
VHOSTBLOCK
if which php &>/dev/null; then
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
index index.php;
VHOSTBLOCK
else
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
index index.php index.html;
VHOSTBLOCK
fi
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
# index.php fallback
location / {
try_files \$uri \$uri/ /index.php?\$query_string;
}
VHOSTBLOCK
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
# additional config
include /etc/nginx/snippets/general.conf;
VHOSTBLOCK
if ! ${_REDIRECT_HTTPS:-false}; then
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
include /etc/nginx/snippets/letsencrypt.conf;
VHOSTBLOCK
fi
if [ -d "/usr/share/phpmyadmin" ]; then
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
include /etc/nginx/snippets/phpmyadmin.conf;
VHOSTBLOCK
fi
if [[ -f "/var/www/${_DOMAIN:-}/public/wp-config.php" ]]; then
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
include /etc/nginx/snippets/wordpress.conf;
VHOSTBLOCK
fi
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
# handle .php
location ~ \.php\$ {
include /etc/nginx/snippets/fastcgi-php.conf;
}
}
##
# CDN for static contents
##
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name cdn.${_DOMAIN:-};
root ${_PATH_WEBROOT:-};
# SSL
ssl_certificate ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/fullchain.pem;
ssl_certificate_key ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/privkey.pem;
VHOSTBLOCK
if [[ "${_VAR[Environment]}" != "vm" ]]; then
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
ssl_trusted_certificate ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/chain.pem;
VHOSTBLOCK
fi
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
# disable access_log
access_log off;
error_log /var/log/nginx/cdn.${_DOMAIN:-}.error.log warn;
# gzip
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
# allow safe files
location ~* \.(?:css(\.map)?|js(\.map)?|ttf|ttc|otf|eot|woff2?|svgz?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv|pdf|docx?|dotx?|docm|dotm|xlsx?|xltx?|xlsm|xltm|pptx?|potx?|pptm|potm|ppsx?)\$ {
add_header Access-Control-Allow-Origin "*";
add_header Cache-Control "public";
expires 360d;
if_modified_since exact;
}
# deny everything else
location / {
deny all;
}
}
VHOSTBLOCK
if ${_REDIRECT_SUB:-false}; then
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
##
# Subdomains Redirect
##
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name *.${_DOMAIN:-};
# SSL
ssl_certificate ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/fullchain.pem;
ssl_certificate_key ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/privkey.pem;
VHOSTBLOCK
if [[ "${_VAR[Environment]}" != "vm" ]]; then
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
ssl_trusted_certificate ${_PATH_LETSENCRYPT_CERTIFICATE}${_DOMAIN:-}/chain.pem;
VHOSTBLOCK
fi
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
return 301 https://${_DOMAIN:-}\$request_uri;
}
VHOSTBLOCK
fi
if ${_REDIRECT_HTTPS:-false}; then
sudo bash -c "cat >> /etc/nginx/conf.d/${_DOMAIN:-}.conf" << VHOSTBLOCK
##
# HTTP to HTTPS Redirect
##
server {
listen 80;
listen [::]:80;
server_name .${_DOMAIN:-};
include /etc/nginx/snippets/letsencrypt.conf;
location / {
return 301 https://${_DOMAIN:-}\$request_uri;
}
}
VHOSTBLOCK
fi
if which php &>/dev/null; then
# Add index.php
if [ ! -f "${_PATH_WEBROOT}/index.php" ]; then
sudo bash -c "cat > ${_PATH_WEBROOT}/index.php" <<INDEXPHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Welcome to ${_SUB:-}${_DOMAIN:-}</title>
<meta name="description" content="Welcome to ${_SUB:-}${_DOMAIN:-}">
<style>.center{text-align: center!important;}</style>
</head>
<body>
<?php echo '<p class="center">Welcome to ${_SUB:-}${_DOMAIN:-}</p>'; ?>
INDEXPHP
if [[ "${_VAR[Environment]}" == "vm" ]]; then
sudo bash -c "cat >> ${_PATH_WEBROOT}/index.php" <<INDEXPHP
<?php phpinfo(); phpinfo(INFO_MODULES);?>
INDEXPHP
fi
sudo bash -c "cat >> ${_PATH_WEBROOT}/index.php" <<INDEXPHP
</body>
</html>
INDEXPHP
fi
else
# Add index.html
if [ ! -f "${_PATH_WEBROOT}/index.html" ]; then
sudo bash -c "cat > ${_PATH_WEBROOT}/index.html" <<INDEXHTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Welcome to ${_SUB:-}${_DOMAIN:-}</title>
<meta name="description" content="Welcome to ${_SUB:-}${_DOMAIN:-}">
<style>.center{text-align: center!important;}</style>
</head>
<body>
<p class="center">Welcome to ${_SUB:-}${_DOMAIN:-}</p>
</body>
</html>
INDEXHTML
fi
fi
fi
sudo nginx -s reload && echo " ✔ The '${_DOMAIN:-}' server block is ready"
}
mysql(){
if which mysql &>/dev/null; then
echo " ✔ The MySQL server is already installed"
else
# MySQL secure installation (set password for root user)
read -p " Enter root (strong) password for MySQL: " -s _ROOT_MYSQL_PASS
echo ""
sudo apt -y install mysql-server
# Install password validation plugin
if [[ $(sudo mysql -u root -e "SELECT PLUGIN_NAME, PLUGIN_STATUS FROM INFORMATION_SCHEMA.PLUGINS WHERE PLUGIN_NAME LIKE 'validate%';" | grep ACTIVE &>/dev/null; echo $?) != 0 ]]; then
sudo mysql -u root <<EOF
INSTALL PLUGIN validate_password SONAME 'validate_password.so';
EOF
fi