Configure Apache in Linux

i) Install Apache server

  • Install Apache server:
    • yum install  httpd
    • systemctl enable httpd        
    • systemctl start httpd            
  • Allow Apache traffic in firewall:
    • firewall-cmd –add-service http –permanent
    • firewall-cmd –reload
  • Configs:
    • /etc/httpd/conf/httpd.conf
    • /etc/httpd/conf.d/ssl.conf
  • Logs:
    • /var/log/httpd/accesss_log
    • /var/log/httpd/error_log
    • /var/log/httpd/ssl_accesss_log
    • /var/log/httpd/ssl_request_log
    • /var/log/httpd/ssl_error_log
  • Notes:
    • ss -tlp | grep httpd                 (Find Apache listening IP and port)
    • ps aux | grep httpd | grep -v grep | wc -l  (Count total httpd process)

ii) Configure Apache over new DocumentRoot and non-standard port:

  1. Create a directory and an index file:
    • mkdir /html
    • echo “Hello World” > /html/index.html
  2. Update the followings in /etc/httpd/conf/httpd.conf:
    • Listen
    • DocumentRoot  “/html”
    • Replace <Directory “/var/www/html”> with <Directory “/html”>
  3. Update SELinux file and ports contexts:
    • chcon -t  httpd_sys_content_t  /html
    • semanage  port  -m  -p tcp  -t http_port_t  88
    • semanage  port  -l | grep http_port_t
  4. Allow the port into firewall:
    • firewall-cmd  –add-port  88/tcp  –permanent
    • firewall-cmd  –reload
  5. Enable and start the service:
    • systemctl  enable  httpd
    • systemctl  start      httpd

(iii) Configure Apache over SSL:

  1. yum install httpd  mod_ssl   
  2. Create two directories, one for certificate and other to serve files:
    1. mkdir  /myssl   /etc/httpd/certs
    2. echo “myssl” > /myssl/index.html                            (Create a index file)    
    3. chcon -R  –reference=/var/www/html   /myssl/    (Set SELinux context)
  3. Create a private key and self-signed certificate:
    • openssl  req  -x509  -nodes  -days 365  -newkey rsa:2048  \
      -keyout /etc/httpd/certs/apache.key  -out /etc/httpd/certs/apache.crt
    • Optional: Append -subj param in above cmd to add certificate details:
      -subj “/C=US/ST=Awesome/L=Town/O=Example Inc /OU=IT/”
    • You may also create the cert by using the following:
      • cd /etc/pki/tls/certs
      • make  /etc/http/certs/apache.crt
      • cd /etc/httpd/certs
      • openssl rsa -in ./apache.key  -out ./apache.key (Remove key password)
  4. Add the followings into /etc/httpd/conf.d/myssl.conf
    Listen 443 https
    <VirtualHost *:443>
    DocumentRoot /myssl/
    <Directory  /myssl/>
    AllowOverride None
    Require all granted
    SSLEngine On
    SSLCertificateKeyFile   /etc/httpd/cert/myssl.key
    SSLCertificateFile         /etc/httpd/certs/myssl.crt      ErrorLog      /var/log/httpd/ssl_error_log
    CustomLog  /var/log/httpd/ssl_access_log  common
  5. Allow https service into firewall:
    • firewall-cmd  –add-service https  –permanent
    • firewall-cmd –reload
  6. systemctl restart httpd

(iv) IP based virtual host:

  1. ip addr add  dev eth0     (Add a second temporary IP)
    • To permanently add the second IP:
      echoIPADDR1=″ >> /etc/sysconfig/network-scripts/ifcfg-eth0
  2. mkdir  /ipvhost
  3. echo “ipvhost”  >  /ipvhost/index.html
  4. chcon -R  –reference=/var/www/html   /ipvhost/              (Set SELinux context)
  5. Add following in /etc/httpd/conf.d/ipvhost.conf
    DocumentRoot   /ipvhost/

           <Directory  /ipvhost/>
                AllowOverride None
                Require all granted
    LogFormat   “%h %l %u %t \”%r\” %>s %b”   ipvhost
    CustomLog   logs/ipvhost-access_log   ipvhost
    ErrorLog      logs/ipvhost-error_log
  6. systemctl reload httpd
  7. w3m -dump

(v) Name based virtual host:

  1. echo “” | tee -a   /etc/hosts
  2. mkdir /namevhost
  3. echo “namevhost”  >  /namevhost/index.html
  4. chcon -t  httpd_sys_content_t  /namevhost/           (Set SELinux context)
  5. Add following in /etc/httpd/conf.d/namevhost.conf
    <VirtualHost _default_:80>                     (Can use *:80 as well)

           DocumentRoot   /var/www/html/
    <VirtualHost *:80>
             DocumentRoot   /namevhost/
             <Directory  /namevhost/>
                   AllowOverride  None
                   Require all granted
             LogFormat  “%h %l %u %t \”%r\” %>s %b”  namevhost
    CustomLog   logs/namevhost-access_log      namevhost
    ErrorLog       logs/namevhost-error_log
  6. systemctl reload httpd
  7. w3m  -dump

(vi) Password protected directory:

  1. echo “Secure file”  | tee /var/www/html/secure.html
  2. Add following in /etc/httpd/conf.d/secure.conf
    <Location /secure/>      #It’s just a virtual path in the URL to match against
    AuthType Basic
    AuthName “Restricted Area”
    AuthUserFile secure.users
    Require valid-user

    RewriteEngine on              # Serve following file just for testing
    RewriteRule   “/secure/”   “
  3. Create a password file and an entry for a user myuser
    htpasswd -c /etc/httpd/secure.users myuser
  4. systemctl reload httpd

(vii) A new cgi scripts enabled directory and url rewriting:

  1. mkdir /cgi-new
  2. Create following foo.cgi script in /cgi-new/ directory:
    echo -e “\n”
    echo -e “Content-type: text/plain\n\n”
    echo -e “File is $1\n”
  3. Grant permissions and update SELinux context:
    chmod -R 755 /cgi-new
    chcon   -R –reference=/var/www/cgi-bin  /cgi-new/
  4. Create newcgi.conf config file in /etc/httpd/conf.d/ with the followings:
    Maps /foo to /scripts/ and pass /bar as argument to script
    RewriteEngine on
    RewriteRule  ^/foo/(.*)   /scripts/foo.cgi?$1 [L,PT]  
    ScriptAlias /scripts  /cgi-new/        (Serves /scripts url from /cgi-new directory)
    <Directory /cgi-new/>
       Require all granted
  5. systemctl restart httpd
  6. curl http://localhost/foo/bar  -> foo.cgi would be: File is bar

P.S. Add “LogLevel alert rewrite:trace6” in /etc/httpd/conf/httpd.conf to print url rewriting debug messages. Reference:

(viii) wsgi scripts enabled directory:

  1. mkdir /wsgi
  2. Create the following webapp.wsgi script in /wsgi/ directory:
    def application(environ, start_response):
    status = ‘200 OK’
    output = ‘Hello World!\n’
    response_headers = [(‘Content-type’, ‘text/plain’), (‘Content-Length’, str(len(output)))]
    start_response(status, response_headers)
    return [output]
  3. Grant permissions and update SELinux context:
    • chmod -R 755 /wsgi
    • chcon -R –reference=/var/www/html  /wsgi/
  4. Create wsgi.conf config file in /etc/httpd/conf.d/ as:
    #All requests /wsgi/* will be handled by /wsgi/webapp.wsgi
    WSGIScriptAlias  /wsgi  /wsgi/webapp.wsgi 
    <Directory /wsgi>
    require all granted
  5. systemctl restart httpd
  6. curl http://localhost/wsgi/

(ix) Enable mod_status:

  1. Add the followings in /etc/httpd/conf.d/status.conf
    <Location /server-status/>
         SetHandler server-status
         Require ip ::1 127.
  2. systemctl restart httpd
  3. w3m -dumb http://localhost/sever-status/

(x) Enable include under URI:

  1. Create two directories under /var/www/html/:
    mkdir /var/www/html/magic  /var/www/html/includes
  2. Add the following into /etc/httpd/conf.d/magic.conf
    <Location /magic/>
         Options +Includes
         XBitHack on
  3. Create index.html in /var/www/html/magic
    <title>This file is a magic include file</title>
    <h1>This file is a magic include file</h1>
    <h2>Foo include below</h2>
    <!–#include virtual=”/includes/foo.html” –>
    <h2>Bar include below</h2>
    <!–#include virtual=”/includes/bar.html” –>
  4. Create foo.html and bar.html in /var/www/html/includes
    echo “foo file include” | tee /var/www/html/includes/foo.html
    echo “bar file include” | tee /var/www/html/includes/bar.html
  5. systemctl restart httpd
  6. curl http://localhost/magic/index.html

(xi) Redirect all requests from http to https:
RewriteEngine  on
RewriteRule      ^(/.*)$  https://%{HTTP_HOST}$1  [redirect=301]

(x) Apache load testing utilities:

  1. Apachebench (ab): provided as part of the Apache httpd server package.
  2. httperf: was written at HP Labs and can use log files as source of URIs to test.
  3. siege: was designed to let web developers measure their code under duress.
  4. sproxy: works as an http proxy server, collecting all information and URIs to use as the Siege testing corpus.

(xi) Alternate web servers:

  1. cherokee: has an innovative web based configuration panel. Benchmarks has shown cherokee to be much faster than Apache for dynamic and static content.
  2.  nginx: it has small footprint, so it scale well from small servers to high performance web servers. It powers some of the largest sites on the Internet, and now accounts 14% of the web server market share.
  3. Lighttpd: is used to power some high-profile sites, such as YouTube and Wikipedia. It has light-weight and scale-able architecture as well.
Posted in LFCE | Tagged ,

Configure DNS server in linux

Configure a Caching DNS:

  • yum install bind
  • /etc/named.conf
    listen-on port 53 { any; }; | {;};
    allow-query { any; };         | { localhost;; };
  • systemctl restart named
  • dig @localhost|@hostname

Configure Authoritative forward zone:

  1. Append following in /etc/named.conf
    zone “” IN {

               type master;
               file “”;
  2. Check config errors:
    named-checkconf     /etc/named.conf
  3. Create a file in /var/named/ with following:
    $TTL 30
    @ IN SOA localhost. (
    2012092901 ; serial YYYYMMDDRR format
    3H ; refresh
    1H ; retry
    2H ; expire
    1M) ; neg ttl
                                         IN NS localhost.; IN A IN AAAA fe80::22c9:d0ff:1ecd:c0ef IN A IN CNAME
    ;generate one hundred entries host1 thru host100
    $GENERATE 1-100 host$ IN A 10.20.45.$
  4. Check zone config:
    named-checkzone /var/named/
  5. systemctl restart named
  6. Test new DNS entries:
    • dig @localhost -t A
    • dig @localhost -t AAAA
    • dig @localhost -t A
    • dig @localhost -t CNAME
    • dig @localhost -t A
    • dig @localhost -t A

Configure a Reverse DNS zone:

  1. Append following in /etc/named.conf:
    zone “” IN {
               type master;
               file “”;
  2. Check config errors:
    named-checkconf     /etc/named.conf
  3. Create a zone file in /var/named/ with following:
    $TTL 30
    @ IN SOA localhost. (
    2012092901 ; serial YYYYMMDDRR format
    3H ; refresh
    1H ; retry
    2H ; expire
    1M) ; neg ttl
    @ IN NS localhost.;
    ;generate 1-254
    $GENERATE 1-254 $ IN PTR host$
  4. Test configs as:
    named-checkzone /var/named/
  5. Reload named daemon:
    rndc reload
  6. Test new DNS entries:
    • host localhost
    • host localhost
    • host localhost


  • A: Return 32bit IPv4 address (name to IP address)
  • AAAA: Return 128bit IPv6 address (name to IP address)
  • PTR: Pointer to cannonical name (IP address to name)
  • CNAME: Return an alias to another name
  • MX: Return the message transfer agents for a domain
  • NS: Delegates an authoritative DNS zone nameserver
  • SOA: Start of Authority for a domain (domain and zone settings)
  • TXT: Arbitrary human-readable text, or machine-readable data for specific purpose



Posted in LFCE

Setup Gate One Web Terminal in CentOS 7

  1. yum  install   epel-release
  2. yum update && yum install   git   python   python-pip
  3. pip install –upgrade  pip  setuptools
  4. git clone
  5. python  ./GateOne/  install
  6. firewall-cmd –add-service https –permanent; firewall-cmd –reload
  7. https://centos-ip
Posted in Linux | Tagged , ,

Recover root password in CentOS

Recover the root password(Without using Live CD or external media)

  1.  Reboot the system and interrupt the boot loader countdown by any key
  2. Use the cursor to highlight the default boot loader entry
  3. Press ‘e’ to edit the entry
  4. Move cursor to kernel command line linux16 and press end key
  5. Append rd.break to the end of the line
  6. Press ctr+x to continue the boot with the changes
  7. mount -o remount,rw /sysroot
  8. chroot /sysroot
  9. echo passw0rd | passwd –stdin root
  10. touch  / .autorelabel
  11. Type exit twice
Posted in LFCS, Linux

Kernel parameters, module and resource limits

Configure Kernel parameters at run-time:

  • sysctl -a
  • sysctl kernel.pid_max; cat /proc/sys/kernel/pid_max
  • sysctl kernel.pid_max=3000; echo 3000 > /proc/sys/kernel/pid_max
  • sysctl -p               (reloads the config param from /etc/sysctl.conf )
  • sysctl –system   (reload the config param from /etc/sysctl.d/99-sysctl.conf)
  • Configs:
    • /etc/sysctl.conf 
    • /etc/sysctl.d/*.conf

Resource limits (/etc/security/limits.conf) :
: Maximum or upper limit value that can one be set by root
Soft: The current value that a user can modify up to hard limit

  • ulimit -a
  • ulimit -n|-u   [-H|-S]
  • ulimit -n|-u  value;
  • ulimit -n|-u hard
  • -n: (nofile -> max number of open file descriptors)
  • -u: (nproc  -> max number of processes)
  • Config:
    • /etc/security/limits.conf
    • /etc/security/limits.d/*.conf
    • *|@grp|user  hard   nproc   3000
    • *|@grp|user  soft     nproc   3000
    • *|@grp|user  hard   nofile   3000
    • *|@grp|user  soft     nofile   3000

List, Add or Remove modules from Kernel:

  • lsmod
  • modinfo dummy
  • modprobe module; insmod /tmp/module.ko
  • modprobe -r module; rmmod module
  • depmod
  • /lib/modules/$(uname –r)/
  • Configs:
    • /etc/modprobe.d/*.conf
    • /etc/modprobe.d/blacklist.conf       (Black list a device or hardware)
Posted in LFCS, Linux

Systemd and SysVinit commands


  • systemctl list-units –type=service|socket [–all] \
  • systemctl list-unit-files  –type=service|socket [--state=enabled|disabled|static]
  • systemctl daemon-reload        (Reload systemd manager configuration)
  • systemctl –failed                       (Show failed services at boot)
  • systemctl start|stop|status|restart|reload|show|mask  foo.service
  • systemctl enable|disable    foo.service
  • systemctl is-enabled|is-active   foo.service   (Returns if service is running|enabled)
  • systemctl cat|edit –full     foo.service            (Show and Edit service unit file)
  • systemctl list-dependencies  [foo] [ | grep target]
  • systemctl list-jobs
  • systemctl reboot|shutdown | rescue       (Boot into rescue mode) 
  • systemd target:
    • Multi user and graphical and text based logins
    • Multi user and text-based logins only
    • sulogin, basic system init completed
    • sulogin prompt, initramfs and mounted on / read-only
    • systemctl list-dependencies | grep target
    • systemctl list-units –type=target –all
    • systemctl list-unit-files –type=target –all
    • systemctl start gdm; telinit 5                     (Starts graphical interface)
    • systemctl get-default                                    (Show the default run level target)
    • systemctl set-default    (Sets default target)
    • systemctl isolate              (Change target immediately)
      • systemctl status
      • runlevel; who -r                                   (Show current run level or target)
    • (Press ‘e‘ during boot and sets target, press ctr+x)
    • Select a Boot Target:
      • During reboot interrupt the boot leader menu countdown by any key
      • Press ‘e‘ to  edit the current entry
      • Move the cursor to the start of line linux16 and press end key
      • Append in the end |
      • Press ctrl+x key to boot with the changes
      • mount -o remount,rw /   (In emergency mode  / is mounted as read-only)
  • Configs
    • /etc/systemd/system/
    • /lib/systemd/system/
  • man pages:
    • man systemd.service                              (Examples of service unit config file)
    • man systemd.resource-control             (Service resource control in foo.slice)


  • hostnamectl status|set-hostname  myhost.local      (/etc/hostname)
  • timedatectl status|set-time|set-timezone|list-timezones  (List and set date/time)
  • systemd-delta                                                   (Find overridden config files)
  • loginctl list-users|list-session|show-user user
  • localectl   [set-locale|set-keymap]
  • systemd-analyze  [blame|critical-chain]      (Analyze system boot up performance)
  • journalctl: (/etc/systemd/journal.conf; /run/log/journal/)
    • journalctl  –xb|k|-b                                    (-xb -> View boot logs)
    • journalctl -p err  |-b-1 -p err                     (Show errors)
    • journalctl –since today
    • journalctl –since “2017-11-28”  –until “2017-11-29”
    • journalctl _UID=1234|_PID=1234
    • Persistence:
      • mkdir -m2755  /var/log/journal     (chmod 2755 /var/log/journal)
      • chgp sytemd-journal  /var/log/journal
      • killall -USR1 systemd-journald


  • chkconfig   –add|–del  foo       = systemctl daemon-reload
  • chkconfig  –list                           = systemctl list-unit-files –type=service
  • chkconfig  [–level 0123456]  foo on|off  = systemctl enable|disable foo
  • service foo start|stop|status  [-all]  = systemctl start|stop|status foo
  • Config:
    • /etc/init.d/
    • /etc/rc.d/init.d/
  • Levels:
    • 0 = Shutdown | Poweroff
    • 1 = Single User Mode
    • 2 = Multiple users, with text login and no NFS
    • 3 = Multiple users with text login, NFS & Network
    • 4 = Not used
    • 5 = Multiple users with graphical login, NFS & Network
    • 6 = Reboot
Posted in LFCE, LFCS, Linux

Disk partitioning, formatting, usage and mount

Disk Partitioning:

  • Manage disk partitions:
    • fdisk /dev/sda
    • parted /dev/sda 
    • partprobe -s  /dev/sda                         (Reload partition table)
  • List disk partitions:
    • fdisk -l ;     fdisk – l  /dev/sda
    • parted -l;  parted   /dev/sda   print 
    • lsblk            [/dev/sda]
    • blkid  /dev/sda                (List label and UUID disk partition attributes)
    • cat /proc/partitions

Disk formatting:

  • mkfs:   (-t -> type; -L -> label; -b -> block size in 1024|2048/4096)
    • mkfs -t ext4|xfs -L MyDisk -b 1024 /dev/sdb1
    • mkfs.ext4  /dev/sdb1 | imgfile
    • mkfs.xfs  /dev/sdb1 | imgfile
  • fsck   -n|-r    /dev/sdb1     (-n -> report only, -r-> repair) 
  • tune2fs(-l -> list; -L -> label; -i -> check interval, -c -> mount count, -m -> block %)
    • tune2fs -l   /dev/sda1                     (List ext4/3/2  file-system attributes)
    • tune2fs -l | grep -i “block size”   (Get block size of file system)
    • tune2fs -L  SDB1  /dev/sdb1          (Change filesystem label)
    • tune2fs  -i|-c|-m 10  /dev/sdb1 
  • dumpe2fs /dev/sda1                                 (Dump ext4/3/2 file system info)
  • xfsdump; xfsrestore; xfs-freeze
  • e4defrag -c /dev/sdb1; e4defrag /var/log

Filesystem / Disk Usage:

  • df -hT        (Show disk usage and filesystem mount)
  • du:             (Show file system space usage)
    • du -csh /dir/*                           (List size of /dir directory and sub-directories )
    • du -hxd 1 /     | sort -h           (Show size of / directories and sort by size)
    • du -cshx /* -exclude=proc | sort -rh  (Show size of / directories)

Add a swap file:

  1. Create a file and grant permissions:
    • dd if=/dev/zero of=~/swap   bs=1M   count=1024
    • chown root:root ~/swap
    • chmod 600 ~/swap
  2. Makeup and enable swap file:
    • mkswap   ~/swap
    • swapon    /root/swap
  3. Mount swap file into /etc/fstab
    • /root/swap    none   swap   defaults   0  0
  4. Verify swap space:
    • cat /proc/swaps
    • free -mh
  5. (Optional) Remove a swap file:
    • swapoff   /root/swap
    • rm  /root/swap

mount and umount:

  • mount:
    • mount; df -hT; cat /proc/mounts    (Show mounted file systems)
    • mount   /dev/sdb1   /mnt
    • mount   /imgfile      /mnt
    • mount UUID=”372a4b9a-1dfa-4a53-8d68-479c3b43de3b” /mnt
    • mount   host:/export  /mnt                     (Mount a nfs directory)
    • mount -o guest //host/export  /mnt     (Mount samba directory)
    • mount   -a   (Mount all directories from  /etc/fstab)
    • mount   -o  remount   /dev/sdb1     (Remount from /etc/fstab)
    • mount   -o  ro,noexec   /dev/sdb1   /mnt
    • mount   -o loop   /dev/loop1    /mnt
    • mount   -t  tmpfs  -o size=1G   none        /mnt
    • mount   -t  tmpfs  -o size=200M  tmpfs  /mnt
  • umount  /mnt | /dev/sda /imgfile        (Un-mount a directory or file system)
  • /etc/fstab:
    • /dev/sda1   /mnt   ext4   default   0   0
    • /imgfile      /mnt   ext4    loop       0   0
    • nfsserver:/exports   /nfs   nfs   defaults  0  0
  • /etc/exports -> (Mount NFS directory)

Mount a nfs directory on client:

  • ALL: ALL@ : ALLOW  >> nfsserver:/etc/hosts.allow
  • showmount -e nfsserver
  • mount nfsserver:/export  /nfs
  • nfsserver:/export   /nfs   nfs   defaults   0  0 >> /etc/fstab
  • mount -o remount /nfs 

Setup and mount a loop device:

  1. dd if=/dev/zero of=~/img  bs=1024M  count=1
  2. losetup -f img                   (Finds and attach first available loop device)
  3. losetup -l|-a                      (List attached loop devices)
  4. mkfs.ext4  /dev/loop0
  5. mkdir /mnt/loop; chmod  a+rwx  /mnt/loop
  6. mount   /dev/loop0   /mnt/loop
  7. /home/user/img   /mnt/loop   ext4   loop   0  0 -> /etc/fstab
  8. losetup -d  /dev/loop0      (Detach a loop device)


Posted in LFCE, LFCS, Linux