Centos 6
Centos 6
Centos 6
8 NOTES
###########################
### RHEL/CentOS install ###
###########################
### Link for netinstall ##
http://ftp.astral.ro/distros/centos/6.8/os/x86_64/
###########
### yum ###
###########
yum update
# update toate pachetele si dependintele lor
yum search nume_pachet # cauta un anume pachet, pot fi mai multe pachete trecute
yum info nume_pachet # afiseaza detalii despre un anume pachet
yum list nume_pache
# afiseaza informatii despre un anumit pachet, instalat sau nu
yum list nume_pachet\* # afiseaza informatii despre toate pachetele care incep cu un nume
yum list all
# afiseaza toate pachetele disponibile
yum list installed *nume_pachet* # afiseaza pachetele instalate care contine un nume
yum list installed | grep reponame # afiseaza pachetele instalate dintr-un repo
yum list available # afiseaza pachetele disponibile in functie de repo-urile instalate
yum repolist
# afiseaza repo-urile instalate
yum gruplist
# afiseaza
yum install nume_pachet\* # instaleaza toate pachetele care incep cu un nume
yum downgrade nume_pachet
yum provides */nume_pachet # afiseaza fisierele care le detine un pachet
yum -v grouplist kde\* # listeaza toate pachetele ce tin de KDE
yum groupinstall KDE Software Compilation # instaleaza toate pachetele ce tin de KDE
yum groupinstall kde-desktop
yum install @kde-desktop # @ pentru a instala un grup
yum remove nume_pachet
yum groupremove KDE Software Compilation
yum groupremove kde-desktop
yum remove @kde-desktop
yum history list
yum history list nume_pachet
yum repolist all # list all repositories set up on your system
yum exclude=packagename\*
################
### yum.conf ###
################
</edit>
</match>
</fontconfig>
__________________________________________
### Add an user to SUDOERS ###
su
visudo
sergiu
ALL=(ALL) ALL
Or add the user to wheel group and enable wheel from visudo
#############
### Repos ###
#############
rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
# Multimedia #
rpm -Uvh http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm
rpm -Uvh http://li.nux.ro/download/nux/dextop/el6/x86_64/nux-dextop-release-02.el6.nux.noarch.rpm
sudo wget http://li.nux.ro/download/nux/misc/nux-misc.repo -P /etc/yum.repos.d/
sudo yum enablerepo=nux-dextop-testing install xbmc
# nVidia driver #
rpm -Uvh http://elrepo.org/elrepo-release-6-5.el6.elrepo.noarch.rpm
http://elrepo.org/linux/extras/el6/x86_64/RPMS/ # extras
http://elrepo.org/linux/testing/el6/x86_64/RPMS/ # testing
sudo yum install kmod-nvidia
sudo yum install nvidia-x11-drv
# Last kernel & lts kernel #
http://elrepo.org/linux/kernel/el6/x86_64/RPMS/ # kernel
sudo yum remove kernel-headers kernel-firmware
sudo yum enablerepo=elrepo-kernel install kernel-ml kernel-ml-devel kernel-ml-headers
kernel-ml-firmware # for last kernel
sudo yum enablerepo=elrepo-kernel install kernel-lt kernel-lt-devel kernel-lt-headers kernel-ltfirmware # for lts kernel
# Others #
rpm -Uvh http://download1.rpmfusion.org/free/el/updates/6/x86_64/rpmfusion-free-release-60.1.noarch.rpm http://download1.rpmfusion.org/nonfree/el/updates/6/x86_64/rpmfusion-nonfreerelease-6-0.1.noarch.rpm # (not needed if nux-dextop is installed)
### Disable window move with alt + left mouse button ###
# conf-editor
# /apps/metacity/general
# mouse_button_modifier option change <Alt> to <Super>
####################################
### CentOS Protection & Security ###
####################################
# Securing and Hardening Red Hat Linux Production Systems
http://www.puschitz.com/SecuringLinux.shtml
https://access.redhat.com/site/documentation/enUS/Red_Hat_Enterprise_Linux/6/html/Security_Guide/index.html
### SElinux ###
Two important documentations about Selinux can be found here:
http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/SecurityEnhanced_Linux/index.html
http://docs.redhat.com/docs/enUS/Red_Hat_Enterprise_Linux/6/html/Managing_Confined_Services/index.html
# You can view current status of SELinux mode from the command line using these:
system-config-selinux
getenforce # if you get back a 1 selinux is turned on if you get back a 0 its turned off
sestatus
# If it is disabled, enable SELinux using the following command.
setenforce enforcing # changes do not persist through a system reboot
To make changes persistent through a system reboot, edit the SELINUX= line in
/etc/selinux/config for either enforcing, permissive, or disabled. For example:
SELINUX=permissive
# SElinux logs (/var/log/audit/audit.log) #
yum install setroubleshoot
setroubleshootd
sealert -a /var/log/audit/audit.log # if you only have a console available and no X-Window
System
sealert -b # if you have gui
# SElinux re-labelling #
touch /.autorelabel
sudo reboot
### Password Protect Grub and Single-User Mode ###
# It is highly important to protect your bootloader.
# There is a magic kernel parameter called init=/bin/sh. This makes any user/login restrictions
totally useless. Then mount -o remount,rw /
8
grub-crypt
vim /etc/grub.conf
______________________________________________
default=0
timeout=2
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
password encrypted $6$w1lrwrXOMm5ueR4M$..
______________________________________________
vim /etc/sysconfig/init
_______________________
PROMPT=no
SINGLE=/sbin/sulogin
_______________________
### Modifying fstab ###
vim /etc/fstab
____________________________________________________________________
/dev/sda1 /boot ext4 defaults,nosuid,noexec,nodev 1 2
/dev/sda2 swap swap defaults
00
/dev/sda3 / ext4 defaults
11
/dev/sda4 /home ext4 defaults,nosuid,nodev
12
# Others partitions
/tmp ext4 defaults,nosuid,noexec,nodev 1 2
/var/tmp ext4 defaults,nosuid,noexec,nodev 1 2
/var ext4 defaults,nosuid
12
/var/www ext4 defaults,nosuid,nodev
12
/dev/shm tmpfs
defaults
00
devpts
/dev/pts devpts gid=5,mode=620
sysfs
/sys sysfs defaults
00
proc
/proc proc defaults
00
00
____________________________________________________________________
# Note that some packages (building nvidia-dkms for example) may require exec on /var
# Keep /boot as read-only #
# Note that you need to reset the change to read-write if you need to upgrade the kernel in future
/dev/sda1 /boot ext4 defaults,nosuid,noexec,nodev,ro 1 2
### Disable Control -Alt -Delete keys on the console mode ###
vim /etc/init/control-alt-delete.conf
______________________________
9
# start on control-alt-delete
# exec /sbin/shutdown -r now Control -Alt -Delete pressed
______________________________
### Umask restrictions ###
# Set a umask of 077 for maximum security, which makes new files not readable by users other
than the owner.
perl -npe s/umask\s+0\d2/umask 077/g -i /etc/bashrc
perl -npe s/umask\s+0\d2/umask 077/g -i /etc/csh.cshrc
### Find users with empty passwords ###
awk -F: ($2 == ) {print} /etc/shadow # Shouldnt see anything amiss here
awk -F: ($3 == 0) {print} /etc/passwd # Only the root user has uid 0. No other user should
ever have uid 0
### Disable USB mass storage ###
echo Disabling USB Mass Storage
echo blacklist usb-storage > /etc/modprobe.d/blacklist-usbstorage
### Disable USB stick to detect ###
vim /etc/modprobe.d/no-usb
_____________________________
install usb-storage /bin/true
_____________________________
### Narrowing rights ###
chmod 700 /root
# before 0550 dr-xr-x
chmod 700 /var/log/audit
# before 0750 drwxr-x
chmod 740 /etc/rc.d/init.d/iptables # before 0755 -rwxr-xr-x
chmod -R 700 /etc/skel
# before 0755 drwxr-xr-x
chmod 640 /etc/security/access.conf # before 0644 -rw-rr
chmod 600 /etc/sysctl.conf
# before 0644 -rw-rr
########################
### Network Security ###
########################
### Sysctl ###
vim /etc/sysctl.conf
_______________________________________________
### ipv4 Security options ###
# Disable IP Source Routing #
# Source Routing is used to specify a path or route through the network from source to
destination.
# This feature can be used by network people for diagnosing problems.
10
# However, if an intruder was able to send a source routed packet into the network, then he could
intercept the replies and your server might not know that its not communicating with a trusted
server.
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
# Disable ICMP Redirect Acceptance #
# ICMP redirects are used by routers to tell the server that there is a better path to other networks
than the one chosen by the server.
# However, an intruder could potentially use ICMP redirect packets to alter the hostss routing
table by causing traffic to use a path you didnt intend.
net.ipv4.conf.all.accept_redirects = 0
# Enable IP Spoofing Protection #
# IP spoofing is a technique where an intruder sends out packets which claim to be from another
host by manipulating the source address.
# IP spoofing is very often used for denial of service attacks.
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Enable Ignoring to ICMP Requests #
net.ipv4.icmp_echo_ignore_all = 1
# Enable Ignoring Broadcasts Request #
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Enable Bad Error Message Protection #
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Enable Logging of Spoofed Packets, Source Routed Packets, Redirect Packets #
net.ipv4.conf.all.log_martians = 1
# This help a little wtih SYN flood attacks. This suppliments a good firewall ruleset #
net.ipv4.tcp_syncookies = 1
# This is a server, not a router. Disable packet forwarding #
net.ipv4.ip_forward = 0
# Others ipv4 security options #
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.tcp_max_syn_backlog = 1280
net.ipv4.tcp_timestamps = 0
11
12
### dd ###
# format a USB #
dd if=/dev/zero of=/dev/sdX
# see the progress of dd #
ps -A | grep dd
sudo kill -USR1 {nr of PID}
### mc ###
gnome-terminal geometry=23968 -e mc -S featured.ini
### GIT HUB ###
ssh-keygen -t rsa -C contact.sergiuniculescu@gmail.com
vim ~/.ssh/id_rsa.pub # copy key and paste it to github.com
git config global user.name Sergiu Niculescu
git config global user.email contact.sergiuniculescu@gmail.com
### Kernel compile ###
yum install gcc ncurses ncurses-devel
yum update
wget http://www.kernel.org/pub/linux/kernel/v3.0/linux-3
tar -jxvf linux-3*
cd linux-3*
make menuconfig # allows you to select the already running kernels configuration file (resides
in /boot/), and accepts the defaults for all options that were introduced between the old and the
new version of the kernel
make oldconfig # automatically finds the configuration file in /boot/ and asks you questions for
all the new configuration options
make
make modules_install install
### Find commands ###
find /home -iname name # Files Using Name and Ignoring Case
find / -type d -name directory_name # Find Directories Using Name
find / -perm /u=r # Find all Read Only files
find / -perm /a=x # Find all Executable files
find . -type f -perm 0777 -print # Find all the files whose permissions are 777
find / -type f -perm 0777 -print -exec chmod 644 {} \; # Find all 777 permission files and use
chmod command to set permissions to 644
find / -type d -perm 777 -print -exec chmod 755 {} \; # Find Directories with 777 Permissions
and Chmod to 755
find . -type f -name tecmint.txt -exec rm -f {} \; # To find a single file called tecmint.txt and
remove it
find . -type f -name *.mp3 -exec rm -f {} \;
# Find and remove Multiple File with
extension .mp3
find /tmp -type f -empty # To file all empty files under certain path
14
find /tmp -type d -empty # To file all empty directories under certain path
find /tmp -type f -name .* # File all Hidden Files
find / \( -perm -4000 -o -perm -2000 \) -print # Identify unwanted SUID and SGID Binaries
find / -path -prune -o -type f -perm +6000 -ls # Identify unwanted SUID and SGID Binaries
find /dir -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print # Identify world writable files
find /dir -xdev \( -nouser -o -nogroup \) -print # Identify orphaned files and folders
### Netstat commands ###
netstat -a | more # Listing all the LISTENING Ports of TCP and UDP connections
netstat -at
# Listing only TCP (Transmission Control Protocol) port connections
netstat -au
# Listing only UDP (User Datagram Protocol ) port connections
netstat -l
# Listing all active listening ports connections
netstat -lt
# Listing all active listening TCP ports
netstat -lu
# Listing all active listening UDP ports
netstat -lx
# Listing all active UNIX listening ports
netstat -s
# Showing Statistics by Protocol
netstat -r
# Display Kernel IP routing table
### Change the MAC address of Network Interface ###
ifconfig eth0 hw ether AA:BB:CC:DD:EE:FF
### Mount an ISO Image ###
mount -t iso9660 -o loop /home/tecmint/Fedora-18-i386-DVD.iso /mnt/iso/
sudo umount /mnt/iso
### Mount a partition with read-write permission ###
mount -o remount,rw /
### Clone the boot partition ###
sudo dd if=/dev/sdb1 of=/dev/sdc1 bs=4096 conv=notrunc,noerror
dd if=/dev/sdb of=mbr.img bs=512 count=1
dd if=mbr.img of=/dev/sdc bs=446 count=1 # If you only want to restore the boot loader
dd if=mbr.img of=/dev/sdc bs=1 skip=446 count=64 # To restore only the partition table
### rsync ###
rsync -a progress rsync://ftp.astral.ro/distros/centos/6.8/os/x86_64/ /opt/mirror/centos
system-config-kickstart # A graphical interface for making kickstart files
#############
### Games ###
#############
### UrbanTerror ###
tar -xjvf UrbanTerror42.tar.gz
cd UrbanTerror42
15
1. Apache Documentation
The documentation from Apache: Upgrading to 2.4 from 2.2 provides the following basic
examples. The old configuration settings are on the left, and the new ones for Apache 2.4 on the
right:
All requests are denied:
Order deny,allow Deny from allRequire all denied
16
In both cases we set an environmental variable PROTECTED when the request is for a file in the
/admin/or /secure/ directories. The syntax for this part hasnt changed. If this variable is set,
then a password will be required for access.
While the old syntax works, its not immediately clear how it works. Basically to get access the
request has to meet (Satisfy) either the Allow or the Require directive.
In the new syntax this is more explicit. The request needs to pass at least one (RequireAny) of
the twoRequireAll container rulesets. The first container grants all users access to nonPROTECTED directories, while the second container requires a valid login.
You can keep nesting containers until all possible options are covered.
But seeing as the outer <RequireAny> is already implied, we should be able to remove it.
Actually we can remove quite a bit now that we know what were doing:
AuthType Basic AuthName "Password Protected" AuthUserFile
<path_to_your_htpasswd_file> SetEnvIf REQUEST_URI "^/(admin|secure)/"
PROTECTED <RequireAll> Require not env PROTECTED </RequireAll> Require validuser
Note that any Require not directives must always be enclosed in a RequireAll directive.
Otherwise you will see an alert logged:
[core:alert] ... negative Require directive has no effect in <RequireAny>
directive
See further down the page a version of this example that does away with the ENV variable
entirely by using an expr condition.
The Require directive comes with a number of build-in authorization providers, including some
already demonstrated above. Different modules provide different methods.
The following are provided by the mod_authz_core module:
all
Replaces Allow from all and Deny from all in the old syntax:
Require all grantedRequire all denied
env
Require env safe_zone<RequireAll> Require not env PROTECTED </RequireAll>
method
This example allows only GET and HEAD requests unless you are logged in:
<RequireAny> Require method GET HEAD Require valid-user </RequireAny>
The <RequireAny> container is not necessary here, but included for clarity:
expr
Require expr %{HTTP_USER_AGENT} != 'BadBot'
ip
<RequireAll> Require ip 192.168.1.0/24 Require not ip 192.168.1.104
</RequireAll>Require ip 2001:db8:1:1::/64
host
<RequireAll> Require host example.org Require not host blocked.example.org
</RequireAll>
The tricky part was working out how to include the forward slash / in the regular expression.
The solution is instead of the default format which doesnt allow a forward slash in the match:
Require expr %{REQUEST_URI} !~ /expr/
For details on other SERVER variables and comparison operators that can be used see the link
under References below.
The local Requirement matches requests from the local host over IPv4 or IPv6 (so including
127.0.0.1/8 and ::1). We wrap this, along with Require ip 192.168.1, in a RequireAny
authorization container because we want to accept connections that match either condition.
We could also write 192.168.1.0/24 instead of just 192.168.1, but they have the same effect.
If you want to also allow connections from outside the local network, but requiring
authentication, the configuration becomes:
<Directory "/path/to/your/website"> Options FollowSymlinks AllowOverride None
Require local Require ip 192.168.1 Require valid-user </Directory>
So were now granting access from localhost and the local network without authentication, plus
from all other locations, but then requiring authentication.
You can make this more secure by restricting outside access to only recognised locations:
19
Now an external connection can only come from *.example.org and only in conjunction with a
valid login. To specify more than one domain or ip address in addition to example.org they will
need to be wrapped in yet another container:
<Directory "/path/to/your/website"> Options FollowSymlinks AllowOverride None
Require local Require ip 192.168.1 <RequireAll> <RequireAny> Require host
example.org example.com Require ip 8.8.8.8 </RequireAny> Require not host
badhost.example.org Require valid-user </RequireAll> </Directory>
For those getting confused, RequireAll means that all the requirements in that container need to
be met, while RequireAny means that only one or more of the contained requirements needs to
be met:
Require (local) OR (ip 192.168.1) OR [ [ (host example.org) OR (host
example.com) OR (ip 8.8.8.8) ] AND (NOT host badhost.example.com) AND (validuser) ]
But what if there is a file ~/private/public.html that you want to make globally accessible?
This wasnt possible in earlier versions of Apache, but can be done now quite simply:
AuthType Basic AuthName "Password Required" AuthUserFile /path/to/.htpasswd
Require expr %{REQUEST_URI} = "/private/public\.html" Require valid-user
How does it work? Remember that there is an explicit <RequireAny> wrapped around the two
Requirestatements, so it reads as: either the request is for the file public.html or require a
password.
June 23rd, 2016 | Category: Apache | Leave a comment
Cause
The qm.ini files had been altered and the LogPath entries were removed.
After making the change to qm.ini LogPath, the queue manager failed to start because
S0000001.log was not available. The log file was present and the permissions appeared to be
correct, but it seemed to be corrupted.
Solution
Edit the qm.ini file and specify the correct LogPath.
If the queue manager fails to start and you suspect a corrupted log file, then do the following:
Here are the steps to follow to recover from the damaged log file(s) in
/var/mqm/log/qmgrname/active. The queue manager is referred to as TESTQMGR.
cd /var/mqm/qmgrs
mv TESTQMGR TEST.OLD
NOTE:This will rename the TESTQMGR directory to be TEST.OLD, effectively backing up all
your queues and objects.
dltmqm TESTQMGR
Note: This command may not completely run and it may produce error messages. This is OK. At
the end of this command there are 3 places to check to make sure everything is cleaned up from
TESTQMGR and if it did not then you will need to manually remove
what is left.
There should not be a directory under /var/mqm/qmgrs by the name of TESTQMGR as it should
have been renamed to TEST.OLD.
In /var/mqm/log there should not be a directory name TESTQMGR. If there is a directory left
there, from /var/mqm/log issue the command rm -rf TESTQMGR to remove the old logs.
In /var/mqm there is a file called mqs.ini. Within file mqs.ini there will be QueueManager:
stanzas for each queue manager defined on this box. There should no longer be a stanza referring
to TESTQMGR. If there is a stanza for TESTQMGR, remove it; the whole
stanza (should be 4 lines.)
crtmqm TESTQMGR
cd /var/mqm/qmgrs
cp TESTQMGR/amqalchk.fil TEST.OLD
(This is to copy the new check point file over to the backup directory where you are saving our
old queue manager files.)
21
rm -rf TESTQMGR
(This will remove the new qmgr files you just created so you can replace them with the files
from the old queue manager that you had saved.)
mv TEST.OLD TESTQMGR
(This is where you just restored the old definitions. At this point you should have a new queue
manager created with new logs but you should have our old queues and channels still there.)
strmqm TESTQMGR
(Start up the queue manager. Everything should be back to normal except there will be no
attempt to recover any in-flight UOWs because you have nothing in the logs.)
another path ?
This typically indicates that the log file is missing or damaged, or that the log path to the queue
manager is inaccessible.
To remedy the problem, create a dummy queue manager and copy its header log file and
transaction log files over to the actual queue manager. This will allow you to restart the queue
manager.
When start being given AMQ7017 MQ queue manager: Log not available, the following
example
$ strmqm
AMQ7017: Log not available.
For this problem solving process is more complex, as an example to the queue manager QM2
about the recovery process:
1, the backup queue manager QM2 objects
22
# su mqm
$ cd /var/mqm/qmgrs
$ mv QM2 QM2_OLD
2, delete the queue manager QM2
$ dltmqm QM2
MQSeries queue manager deleted.
3, delete directory directory /var/mqm/log under the QM2
$ cd /var/mqm/log
$ rm -rf QM2
4? the file does not ensure /var/mqm/mqs.ini QM2 project, if it is deleted.
$ vi /var/mqm/mqs.ini
AllQueueManagers:
DefaultPrefix=/var/mqm
ClientExitPath:
ExitsDefaultPath=/var/mqm/exits
LogDefaults:
LogPrimaryFiles=3
LogSecondaryFiles=2
LogFilePages=1024
LogType=CIRCULAR
LogBufferPages=17
LogDefaultPath=/var/mqm/log
QueueManager:
23
Name=QM3
Prefix=/var/mqm
Directory=QM3
5? re-create the queue manager QM2
$ crtmqm QM2
MQSeries queue manager created.
Creating or replacing default objects for QM2.
Default objects statistics : 29 created. 0 replaced. 0 failed.
Completing setup.
Setup completed.
?? /var/mqm/mqs.ini ?????
$ vi /var/mqm/mqs.ini
AllQueueManagers:
DefaultPrefix=/var/mqm
ClientExitPath:
ExitsDefaultPath=/var/mqm/exits
LogDefaults:
LogPrimaryFiles=3
LogSecondaryFiles=2
LogFilePages=1024
LogType=CIRCULAR
LogBufferPages=17
LogDefaultPath=/var/mqm/log
24
QueueManager:
Name=QM3
Prefix=/var/mqm
Directory=QM3
QueueManager:
Name=QM2
Prefix=/var/mqm
Directory=QM2
6? Copy the new check point before the backup file to a directory in QM2_OLD
$ cd /var/mqm/qmgrs
$ cp QM2/amqalchk.fil QM2_OLD
7 Remove the new queue manager object directory /var/mqm/qmgrs/QM2
$ rm -rf QM2
8?the object manager object data backup to restore the directory to the directory QM2
QM2_OLD
$ mv QM2_OLD QM2
9 start the queue manager QM2, problems get.
$ strmqm QM2
MQSeries queue manager QM2 started.
June 18th, 2016 | Category: MQ Server | Leave a comment
26
27
Wrote: /home/builder/rpmbuild/SRPMS/nginx-1.8.1-1.el7.centos.ngx.src.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-debug-1.8.1-1.el7.centos.ngx.x86_64.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-debuginfo-1.8.11.el7.centos.ngx.x86_64.rpm
Executing(%clean): /bin/sh -e /var/tmp/rpm-tmp.lWzVrm
+ umask 022
+ cd /home/builder/rpmbuild/BUILD
+ cd nginx-1.8.1
+ /usr/bin/rm -rf /home/builder/rpmbuild/BUILDROOT/nginx-1.8.1-1.el7.centos.ngx.x86_64
+ exit 0
As we can see the Nginx RPM package bundled with Pagespeed is saved in ~/rpmbuild/RPMS/
Login as root in able to install the compiled Nginx RPM:
su
You can use yum or rpm to install it:
yum update /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
or:
rpm -Uvh /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
If the current nginx is higher version than we have compiled (like in my case I have nginx
v1.9.4), execute the following to force install the Nginx RPM we have build:
yum downgrade /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.11.el7.centos.ngx.x86_64.rpm
or:
rpm -Uvh oldpackage /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.11.el7.centos.ngx.x86_64.rpm
Make sure it auto-start upon reboot:
chkconfig nginx on
To check if Pagespeed is included in Nginx:
nginx -V
If you dont want to build the RPM in your production server, you may use other machine.
28
In my case, I just build my RPM in my laptop using CentOS 7 64-bit Vagrant box. Just make
sure they have both the same system type (OS and processor).
For PageSpeed Nginx configuration,
May 25th, 2016 | Category: Nginx | Leave a comment
29
Gluster installation :
Retrieve GlusterFS repository : all 3 servers
wget -P /etc/yum.repos.d
http://download.gluster.org/pub/gluster/glusterfs/LATEST/RHEL/glusterfs-epel.repo
Download GlusterFS packages : all 3 servers
yum -y install glusterfs-server
Now, start the service and keep it started across reboot :
[root@apache3 ~]# systemctl start glusterd && systemctl enable glusterd
Created symlink from /etc/systemd/system/multi-user.target.wants/glusterd.service to
/usr/lib/systemd/system/glusterd.service.
[root@apache3 ~]#
Update /etc/hosts :
192.168.1.71 apache1.rmohan.com apache1
192.168.1.72 apache2.rmohan.com apache2
192.168.1.74 apache3.rmohan.com apache3
Check the 2 GlusterFS servers
[root@apache1 ~]# gluster peer probe apache2
peer probe: success.
[root@apache1 ~]# gluster peer probe apache3
peer probe: success.
[root@apache1 ~]#
[root@apache2 ~]# gluster peer probe apache3
peer probe: success. Host apache3 port 24007 already in peer list
[root@apache2 ~]# gluster peer probe apache1
peer probe: success. Host apache1 port 24007 already in peer list
[root@apache2 ~]#
[root@apache3 ~]# gluster peer probe apache1
peer probe: success. Host apache1 port 24007 already in peer list
[root@apache3 ~]# gluster peer probe apache2
peer probe: success. Host apache2 port 24007 already in peer list
[root@apache3 ~]#
Check the Peers :
root@apache1 ~]# gluster peer status
Number of Peers: 2
Hostname: apache2
Uuid: 09db776a-ab96-47a3-ad77-6bc77906566b
State: Peer in Cluster (Connected)
Hostname: apache3
Uuid: 14db2875-378d-481d-968c-552a10f2fd7e
30
32
34
rpm? The process we need is to repackage RPM and that is what this tutorial will show.
Prepare tools
The following procedures are tested on my Linode server running Centos 7 64-bit Linux
distribution.
First we need to install the necessary tools to repackage RPM:
sudo yum install rpm-build gcc-c++ pcre-devel zlib-devel make unzip
It is recommended to not to use root user in building RPM, so we will create a new user:
useradd -m builder
* The -m is to create home directory
Select the latest version of Nginx RPM source here and download (as of this writing the latest is
nginx-1.8.1-1.el7.ngx.src.rpm):
rpm -Uvh http://nginx.org/packages/centos/7/SRPMS/nginx-1.8.1-1.el7.ngx.src.rpm
Move the Nginx RPM source to the new user created builder home directory:
mv /root/rpmbuild /home/builder/ && chown -R builder. /home/builder/rpmbuild
Pagespeed source
Login as builder and go to RPM source directory:
su builder
cd ~/rpmbuild/SOURCES/
Download and extract the latest version of Pagespeed:
wget https://github.com/pagespeed/ngx_pagespeed/archive/release-1.11.33.0-beta.zip
unzip release-1.11.33.0-beta.zip
rm release-1.11.33.0-beta.zip
Inside the extracted Pagespeed source directory, download and extract its required PSOL library:
cd ngx_pagespeed-release-1.11.33.0-beta/
wget https://dl.google.com/dl/page-speed/psol/1.11.33.0.tar.gz
tar -zxvf 1.11.33.0.tar.gz
rm 1.11.33.0.tar.gz
Archive both Pagespeed and PSOL as one:
35
cd ..
tar -zcvf ngx_pagespeed-release-1.11.33.0-beta.tar.gz ngx_pagespeed-release-1.11.33.0-beta/
rm -r ngx_pagespeed-release-1.11.33.0-beta/
cd ~
Enable Pagespeed in Nginx spec
Open and edit nginx.spec file:
vi ~/rpmbuild/SPECS/nginx.spec
Search for Source0: http://nginx.org/download/%{name}-%{version}.tar.gz and add above it:
%define pagespeed_version 1.11.33.0-beta
Note: 1.11.33.0-beta is the version of Pagespeed.
Scroll down and search Source10: nginx.suse.logrotate and add under it:
Source11: ngx_pagespeed-release-%{pagespeed_version}.tar.gz
Again scroll down and search %setup -q and add under it:
%{__tar} zxvf %{SOURCE11}
%setup -T -D -a 11
And scroll down and search with-cc-opt=%{optflags} $(pcre-config cflags) \ and add
under it (Note: there are two of these):
add-module=%{_builddir}/%{name}-%{version}/ngx_pagespeed-release-%
{pagespeed_version} \
And save the nginx.spec file.
Build and install the new Nginx with Pagespeed module
Build the Nginx RPM package:
rpmbuild -ba ~/rpmbuild/SPECS/nginx.spec
After the compilation completed you should see output message at the end something like these:
Wrote: /home/builder/rpmbuild/SRPMS/nginx-1.8.1-1.el7.centos.ngx.src.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-debug-1.8.1-1.el7.centos.ngx.x86_64.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-debuginfo-1.8.11.el7.centos.ngx.x86_64.rpm
Executing(%clean): /bin/sh -e /var/tmp/rpm-tmp.lWzVrm
36
+ umask 022
+ cd /home/builder/rpmbuild/BUILD
+ cd nginx-1.8.1
+ /usr/bin/rm -rf /home/builder/rpmbuild/BUILDROOT/nginx-1.8.1-1.el7.centos.ngx.x86_64
+ exit 0
As we can see the Nginx RPM package bundled with Pagespeed is saved in ~/rpmbuild/RPMS/
Login as root in able to install the compiled Nginx RPM:
su
You can use yum or rpm to install it:
yum update /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
or:
rpm -Uvh /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
If the current nginx is higher version than we have compiled (like in my case I have nginx
v1.9.4), execute the following to force install the Nginx RPM we have build:
yum downgrade /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.11.el7.centos.ngx.x86_64.rpm
or:
rpm -Uvh oldpackage /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.11.el7.centos.ngx.x86_64.rpm
Make sure it auto-start upon reboot:
chkconfig nginx on
To check if Pagespeed is included in Nginx:
nginx -V
If you dont want to build the RPM in your production server, you may use other machine.
In my case, I just build my RPM in my laptop using CentOS 7 64-bit Vagrant box. Just make
sure they have both the same system type (OS and processor).
For PageSpeed Nginx configuration,
May 17th, 2016 | Category: Centos RHEL 7, Nginx | Leave a comment
37
$conf[cache_backends][] = sites/all/modules/memcache/memcache.inc;
$conf[lock_inc] = sites/all/modules/memcache/memcache-lock.inc;
$conf[memcache_stampede_protection] = TRUE;
$conf[cache_default_class] = MemCacheDrupal;
// The cache_form bin must be assigned to non-volatile storage.
$conf[cache_class_cache_form] = DrupalDatabaseCache;
// Dont bootstrap the database when serving pages from the cache.
$conf[page_cache_without_database] = TRUE;
$conf[page_cache_invoke_hooks] = FALSE;
// If this server has multiple Drupal installation
// assign unique key for memcache namespace purposes
$conf[memcache_key_prefix] = www_yoursite_com;
May 17th, 2016 | Category: Centos RHEL 7 | Leave a comment
server {
2015/08/27 02:18:05 [error] 21235#21235: *326 limiting requests, excess: 5.297 by zone one,
client: 91.214.169.44, server: www.webfoobar.com, request: GET /node/8 HTTP/1.1, host:
www.webfoobar.com, referrer: https://www.webfoobar.com/archive/201502
We will use this sample log entry for our fail2ban filter script.
Install fail2ban:
yum install -y fail2ban
Create fail2ban filter script based on the Nginx error log entry:
vi /etc/fail2ban/filter.d/nginx-ddos.conf
The content of this filter file:
[Definition]
failregex = limiting requests, excess:.* by zone.*client:
ignoreregex =
We will use the /etc/hosts.deny to block the IP of the DDoS attacker so we will need to create
new fail2ban action script:
vi /etc/fail2ban/action.d/hostsdeny.conf
Add the following script as its content:
[Definition]
actionstart =
actionstop =
actioncheck =
actionban = IP= &&
printf %%b : $IP\n >>
actionunban = IP= && sed -i.old /ALL:\ $IP/d
[Init]
file = /etc/hosts.deny
daemon_list = ALL
Enable the newly created fail2ban filter:
vi /etc/fail2ban/jail.local
Append the following script:
[nginx-ddos]
enabled = true
40
port = http,https
banaction = hostsdeny
findtime = 120
bantime = 7200
maxretry = 30
logpath = %(nginx_error_log)s
Start the fail2ban service:
systemctl start fail2ban
systemctl enable fail2ban.service
systemctl list-unit-files | grep fail2ban
To check the status of this fail2ban filter:
fail2ban-client status nginx-ddos
You will see something like this:
Status for the jail: nginx-ddos
|- Filter
| |- Currently failed: 18
| |- Total failed: 770
| `- File list:
/var/log/nginx/nginx_error_log
`- Actions
|- Currently banned: 1
|- Total banned: 8
`- Banned IP list: 91.214.169.44
To test if the fail2ban nginx-ddos filter working:
fail2ban-regex /var/log/nginx/nginx_error_log /etc/fail2ban/filter.d/nginx-ddos.conf
You can use apache-bench to test the whole system:
ab -n 20 -c 10 http://www.example.com
Execute the following command to monitor the fail2ban log:
watch -n 1 tail -n 20 /var/log/fail2ban.log
And you will something like this while testing with apache-bench:
May 17th, 2016 | Category: Centos RHEL 7 | Leave a comment
#set_real_ip_from 2606:4700::/32;
#set_real_ip_from 2803:f800::/32;
#set_real_ip_from 2405:b500::/32;
#set_real_ip_from 2405:8100::/32;
#real_ip_header CF-Connecting-IP;
## Timeouts.
client_body_timeout 60;
client_header_timeout 60;
# Timeout for keep-alive connections. Server will close connections after this time.
keepalive_timeout 10 10;
send_timeout 60;
## Reset lingering timed out connections. Deflect DDoS.
reset_timedout_connection on;
## Body size.
client_max_body_size 10m;
## TCP options.
# dont buffer data-sends (disable Nagle algorithm).
# Good for sending frequent small bursts of data in real time.
tcp_nodelay on;
## Optimization of socket handling when using sendfile.
# Tcp_nopush causes nginx to attempt to send its HTTP response head in one packet,
# instead of using partial frames. This is useful for prepending headers
# before calling sendfile, or for throughput optimization.
tcp_nopush on;
## Compression.
# Reduces the amount of data that needs to be transferred over the network
gzip on;
gzip_buffers 16 8k;
gzip_comp_level 1;
gzip_http_version 1.1;
gzip_min_length 10;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml
application/xml+rss text/javascript image/x-icon application/vnd.ms-fontobject font/opentype
application/x-javascript application/x-font-ttf text/x-js;
gzip_vary on;
gzip_proxied any; # Compression for all requests.
gzip_disable MSIE [1-6]\.(?!.*SV1);
## Hide the Nginx version number.
server_tokens off;
## Use a SSL/TLS cache for SSL session resume. This needs to be
## here (in this context, for session resumption to work. See this
## thread on the Nginx mailing list:
## http://nginx.org/pipermail/nginx/2010-November/023736.html.
ssl_session_cache shared:SSL:30m;
ssl_session_timeout 1d;
## The server dictates the choice of cipher suites.
44
ssl_prefer_server_ciphers on;
## No SSL2 support.
## No SSLv3 support (SSLv3 POODLE Vulnerability)
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
## Pregenerated Diffie-Hellman parameters.
ssl_dhparam /etc/nginx/dh_param.pem;
## Curve to use for ECDH.
ssl_ecdh_curve secp521r1;
## Enable OCSP stapling. A better way to revocate server certificates.
ssl_stapling on;
## Enable verification of OCSP stapling responses by the server.
ssl_stapling_verify on;
## Use Googles DNS
resolver 8.8.4.4 8.8.8.8;
## Enable the builtin cross-site scripting (XSS) filter available
## in modern browsers. Usually enabled by default we just
## reinstate in case it has been somehow disabled for this
## particular server instance.
## https://www.owasp.org/index.php/List_of_useful_HTTP_headers.
add_header X-XSS-Protection 1; mode=block;
## Enable this if using HTTPS
#add_header Strict-Transport-Security max-age=7200;
## Block MIME type sniffing on IE.
add_header X-Content-Options nosniff;
## Add a cache miss/hit status header
add_header X-Micro-Cache $upstream_cache_status;
## Block HTTP methods.
map $request_method $not_allowed_method {
default 1;
GET 0;
HEAD 0;
POST 0;
}
## Add as many servers as needed.
## Cf. http://wiki.nginx.org/HttpUpstreamModule.
## Note that this configuration assumes by default that keepalive
## upstream connections are supported and that you have a Nginx
## version with the fair load balancer.
upstream phpapache {
## Use the least connection algorithm for load balancing
least_conn;
server 127.0.0.1:8000;
keepalive 5;
}
## Configuration for reverse proxy. Passing the necessary headers to
## the backend. Nginx doesnt tunnel the connection, it opens a new
45
## one. Hence whe need to send these headers to the backend so that
## the client(s) IP is available to them. The host is also sent.
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
## Hide the Drupal headers
proxy_hide_header X-Drupal-Cache;
proxy_hide_header X-Generator;
## Include blacklist for bad bot and referer blocking.
include blacklist.conf;
## Include the caching setup. Needed for using Drupal with an external cache.
include apps/drupal/drupal_map.conf;
## Defining the proxy cache zone for the microcache as presented at:
## http://fennb.com/microcaching-speed-your-app-up-250x-with-no-n.
proxy_cache_path /var/cache/nginx/microcache levels=1:2 keys_zone=microcache:5M
max_size=1G loader_threshold=2592000000 loader_sleep=1 loader_files=100000;
## To build optimal server_names_hash
server_names_hash_bucket_size 72;
## Include all vhosts.
include /etc/nginx/sites-enabled/*;
}
Create the file /etc/nginx/dh_param.pem and add the following to it:
BEGIN DH PARAMETERS
MIIBCAKCAQEAkD39jm2I+Sr1j1+YPB5TbgUvIWUv3Gzj1s1rtpuZJUhCQ8MElafR
XrjrNXtgN8yjX6J5+Nuj0G9SytrvtKU9T3pLDVjZiV2l0m+/pvzaW3qCSlegpA/S
bkIQPg4n7CP/dhs7JcQD0Ny6TX9iYioDz5/kGfrBHTfAW8A6gPinAiC/+8Osz6mP
UghuQPkFVxJmleIdGU7ll3tAKARJpe8HyHNMNoRGbWTCH1mc8Z/la0E7xjs5R2mh
rYxofg/TMFJyvnnjtTLRQ9edvdA+K9JNsF23t8qvY78ppHNEP7u1PA7ORtePagJk
vcSF5yMYeDzUQLWpOuK5B0yHtltZzANH6wIBAg==
END DH PARAMETERS
Create the file /etc/nginx/blacklist.conf and add the following to it:
## Add here all user agents that are to be blocked.
map $http_user_agent $bad_bot {
default 0;
~*^Lynx 0; # Let Lynx go through
libwww-perl 1;
~(?i)(httrack|htmlparser|libwww) 1;
}
## Add here all referrers that are to blocked.
map $http_referer $bad_referer {
default 0;
~(?i)(adult|babes|click|diamond|forsale|girl|jewelry|love|nudit|organic|poker|porn|
46
poweroversoftware|sex|teen|webcam|zippo|casino|replica) 1;
}
## Add here all hosts that should be spared any referrer checking.
geo $bad_referer {
127.0.0.1 0;
192.168.1.0/24 0;
}
Create the file /etc/nginx/drupal_map.conf and add the following to it:
## Let Ajax calls go through
map $uri $no_cache_ajax {
default 0;
/system/ajax 1;
}
## Check session cookie being present
map $http_cookie $no_cache_cookie {
default 0;
~SESS 1; # PHP session cookie
}
## Combine both results to get the cache bypassing mapping
map $no_cache_ajax$no_cache_cookie $no_cache {
default 1;
00 0;
}
## Cache bypassing mapping (auth).
map $no_cache_ajax $no_auth_cache {
default 0;
1 1;
}
## Set a cache_uid variable for authenticated users.
map $http_cookie $cache_uid {
default nil;
~SESS[[:alnum:]]+=(?[[:graph:]]+) $session_id;
}
Create the file /etc/nginx/drupal.conf and add the following to it:
location / {
## Let Drupal handle 404
error_page 404 /index.php;
## Regular private file serving (i.e. handled by Drupal).
location ^~ /system/files/ {
proxy_pass http://phpapache;
proxy_http_version 1.1; # keep alive to the Apache upstream
proxy_set_header Connection ;
47
}
## Advanced Aggregation module CSS/JS
## support. http://drupal.org/project/advagg.
location ~ ^/sites/[\.\-[:alnum:]]+/files/advagg_(?:css|js)/ {
expires max;
gzip_static on;
add_header ETag ;
add_header Accept-Ranges ;
# Set a far future Cache-Control header to 52 weeks.
add_header Cache-Control max-age=31449600, no-transform, public;
location ~* (?:css|js)[_\-[:alnum:]]+\.(?:css|js)(\.gz)?$ {
access_log off;
try_files $uri $uri/ @drupal-noexp;
}
}
## All static files will be served directly.
location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|htm|html|xml|txt|otf|ttf|eot|woff|svg|webp|webm|
zip|gz|tar|rar)$ {
access_log off;
expires 30d;
## No need to bleed constant updates. Send the all shebang in one
## fell swoop.
tcp_nodelay off;
## Set the OS file cache.
open_file_cache max=3000 inactive=120s;
open_file_cache_valid 45s;
open_file_cache_min_uses 2;
open_file_cache_errors off;
try_files $uri $uri/ @drupal-noexp;
}
## PDFs and powerpoint files handling.
location ~* ^.+\.(?:pdf|pptx?)$ {
access_log off;
expires 30d;
## No need to bleed constant updates. Send the all shebang in one
## fell swoop.
tcp_nodelay off;
try_files $uri $uri/ @drupal-noexp;
}
## MP3 and Ogg/Vorbis files are served using AIO when supported. Your OS must support it.
location ~ ^/sites/[\.\-[:alnum:]]+/files/audio/mp3 {
location ~* .*\.mp3$ {
access_log off;
directio 4k; # for XFS
## If youre using ext3 or similar uncomment the line below and comment the above.
#directio 512; # for ext3 or similar (block alignments)
49
tcp_nopush off;
aio on;
output_buffers 1 2M;
try_files $uri $uri/ @drupal;
}
}
location ~ ^/sites/[\.\-[:alnum:]]+/files/audio/ogg {
location ~* .*\.ogg$ {
access_log off;
directio 4k; # for XFS
## If youre using ext3 or similar uncomment the line below and comment the above.
#directio 512; # for ext3 or similar (block alignments)
tcp_nopush off;
aio on;
output_buffers 1 2M;
try_files $uri $uri/ @drupal;
}
}
## Pseudo streaming of FLV files:
## http://wiki.nginx.org/HttpFlvStreamModule.
## If pseudo streaming isnt working, try to comment
## out in nginx.conf line with:
## add_header X-Frame-Options SAMEORIGIN;
location ~ ^/sites/[\.\-[:alnum:]]+/files/video/flv {
location ~* .*\.flv$ {
access_log off;
flv;
try_files $uri $uri/ @drupal;
}
}
## Pseudo streaming of H264/AAC files. This requires an Nginx
## version greater or equal to 1.0.7 for the stable branch and
## greater or equal to 1.1.3 for the development branch.
## Cf. http://nginx.org/en/docs/http/ngx_http_mp4_module.html.
location ~ ^/sites/[\.\-[:alnum:]]+/files/video/mp4 { # videos
location ~* .*\.(?:mp4|mov)$ {
access_log off;
mp4;
mp4_buffer_size 1M;
mp4_max_buffer_size 5M;
try_files $uri $uri/ @drupal;
}
}
location ~ ^/sites/[\.\-[:alnum:]]+/files/audio/m4a { # audios
location ~* .*\.m4a$ {
access_log off;
50
mp4;
mp4_buffer_size 1M;
mp4_max_buffer_size 5M;
try_files $uri $uri/ @drupal;
}
}
## Advanced Help module makes each module provided README available.
location ^~ /help/ {
location ~* ^/help/[^/]*/README\.txt$ {
access_log off;
proxy_pass http://phpapache;
proxy_http_version 1.1; # keep alive to the Apache upstream
proxy_set_header Connection ;
## Rewrite the Host header to the value in the client request,
## or primary server name
proxy_set_header Host $host;
}
}
## Replicate the Apache directive of Drupal standard
## .htaccess. Disable access to any code files. Return a 404 to curtail
## information disclosure. Hide also the text files.
location ~* ^(?:.+\.(?:htaccess|make|txt|engine|inc|info|install|module|profile|po|pot|sh|.*sql|test|
theme|tpl(?:\.php)?|xtmpl)|code-style\.pl|/Entries.*|/Repository|/Root|/Tag|/Template)$ {
return 404;
}
## First we try the URI and relay to the upstream server if not found.
try_files $uri $uri/ @drupal;
}
## Restrict access to the strictly necessary PHP files. Reducing the
## scope for exploits. Handling of PHP code and the Drupal event loop.
location @drupal {
proxy_pass http://phpapache;
proxy_http_version 1.1; # keep alive to the Apache upstream
proxy_set_header Connection ;
## Rewrite the Host header to the value in the client request,
## or primary server name
proxy_set_header Host $host;
## Proxy microcache
include microcache_proxy.conf;
## The Cache-Control and Expires headers should be delivered untouched
## from the upstream to the client.
proxy_ignore_headers Cache-Control Expires;
## To avoid any interaction with the cache control headers we expire
## everything on this location immediately.
expires epoch;
}
51
vi /etc/logrotate.d/websites_nginx_logs.conf
Content:
/var/log/virtualmin/*nginx_access_log /var/log/virtualmin/*nginx_error_log {
rotate 10
missingok
daily
compress
postrotate
service httpd graceful ; sleep 5
endscript
sharedscripts
}
Configure Apache
Since Nginx is reverse proxy to Apache, the IP address that Apache will get is the IP of the server
and we need to correct that. Apache 2.4 and above do have mod_remoteip and we will use that
module. Open mod_remoteips configuration file:
vi /etc/httpd/conf.d/remoteip.conf
Add the following codes:
# mod_remoteip settings
RemoteIPHeader X-Real-IP
RemoteIPInternalProxy 127.0.0.1
RemoteIPInternalProxy 188.8.8.8
Note: change 188.8.8.8 to your servers IP address.
Change the port of Apache:
vi /etc/httpd/conf/httpd.conf
Look for:
Listen 80
and change to:
Listen 8000
Restart Apache:
systemctl restart httpd.service
55
Configure Virtualmin
Set the virtual server template to listen to 8000. Login to Virtualmin, go to System Settings ->
Server Templates -> Default Settings and select from the dropdown Apache Website.
Change the Port number for virtual hosts from 80 to 8000. Restart webmin:
systemctl restart webmin.service
Lets build the necessary scripts that will automate the creation of Nginx virtual host file each
time Virtualmin created a new server. First the Nginx virtual host template:
vi /etc/nginx/sites-available/template.conf
The content:
## Configuration for {DOM}.
server {
## Replace XXX.XXX.XXX.XXX with your servers IPv4 address
listen XXX.XXX.XXX.XXX:80;
## Replace XXXX:XXXX::XXXX:XXXX:XXXX:XXXX with your servers IPv6 address
listen [XXXX:XXXX::XXXX:XXXX:XXXX:XXXX]:80;
server_name {DOM};
## Redirect permanently to domain with www
return 301 $scheme://www.{DOM}$request_uri;
}
server {
## Replace XXX.XXX.XXX.XXX with your servers IPv4 address
listen XXX.XXX.XXX.XXX:80;
## Replace XXXX:XXXX::XXXX:XXXX:XXXX:XXXX with your servers IPv6 address
listen [XXXX:XXXX::XXXX:XXXX:XXXX:XXXX]:80;
server_name www.{DOM};
## Access and error logs.
access_log /var/log/virtualmin/{DOM}_nginx_access_log;
error_log /var/log/virtualmin/{DOM}_nginx_error_log error;
## Root of the site and index.
root {HOME}/public_html;
index index.php;
## Deny access based on the User-Agent header.
if ($bad_bot) {
return 444;
}
## Deny access based on the Referer header.
if ($bad_referer) {
return 444;
}
## Protection against illegal HTTP methods. Only HEAD,
56
{VIRTUALSERVER_OLDSERVER_DOM}.conf
mv $OLD_NGINX_CONF_FILE $NGINX_CONF_FILE
rm /etc/nginx/sites-enabled/${VIRTUALSERVER_OLDSERVER_DOM}.conf
perl -pi -e s#$VIRTUALSERVER_OLDSERVER_DOM#$VIRTUALSERVER_DOM#g
$NGINX_CONF_FILE
perl -pi -e s#$VIRTUALSERVER_OLDSERVER_IP#$VIRTUALSERVER_IP#g
$NGINX_CONF_FILE
perl -pi -e s#$VIRTUALSERVER_OLDSERVER_HOME#$VIRTUALSERVER_HOME#g
$NGINX_CONF_FILE
ln -s /etc/nginx/sites-available/${VIRTUALSERVER_DOM}.conf /etc/nginx/sites-enabled/$
{VIRTUALSERVER_DOM}.conf
fi
fi
if [ ${VIRTUALSERVER_WEB} = 1 ];
then
nginx -s reload
fi
fi
Make the script executable:
chmod u+x /usr/local/bin/virtualmin.sh
Let Virtualmin know about the virtualmin.sh. Login to Virtualmin, go to System Settings ->
Virtualmin Configuration and select from dropdown Actions upon server and user creation.
Populate the Command to run after making changes to a server field with:
/usr/local/bin/virtualmin.sh
May 17th, 2016 | Category: Nginx | Leave a comment
58
#
country_list = PH|Philippines
# Option: file
# Notes.: hosts.deny file path.
# Values: STR Default: /etc/hosts.deny
#
file = /etc/hosts.deny
# Option: daemon_list
# Notes: The list of services that this action will deny. See the man page
#
for hosts.deny/hosts_access. Default is all services.
# Values: STR Default: ALL
daemon_list = ALL
The script above will exempt from banning the visitors from Philippines which defined in
country_list.
To enable our action script in Fail2Ban:
vi /etc/fail2ban/jail.local
Copy the following line:
banaction = geohostsdeny
Restart Fail2Ban:
systemctl restart fail2ban
60