Set up iptables On Debian 8 Debian 9

Faster way paste this on console

/sbin/iptables -F && /sbin/iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP && /sbin/iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP && /sbin/iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP && /sbin/iptables -I INPUT -p icmp -m icmp --icmp-type echo-request -j ACCEPT && /sbin/iptables -A INPUT -i lo -j ACCEPT && /sbin/iptables -A OUTPUT -o lo -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 21 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 25 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 465 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 110 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 995 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 143 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 993 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT && /sbin/iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT && /sbin/iptables -P OUTPUT ACCEPT && /sbin/iptables -P INPUT DROP

New script only open port 80, 443, 25, 465,587

/sbin/iptables -F && /sbin/iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP && /sbin/iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP && /sbin/iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP && /sbin/iptables -I INPUT -p icmp -m icmp --icmp-type echo-request -j ACCEPT && /sbin/iptables -A INPUT -i lo -j ACCEPT && /sbin/iptables -A OUTPUT -o lo -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 25 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 465 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 587 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT && /sbin/iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT && /sbin/iptables -P OUTPUT ACCEPT && /sbin/iptables -P INPUT DROP

IP-Tables are not persistent On Debian 8, save permanent the new rules to the master iptables file:

#/usr/sbin/iptables-save > /etc/iptables.up.rules

Make sure the iptables rules are started on a reboot we’ll create a new file:

#vim /etc/network/if-pre-up.d/iptables

Add these lines to it:

#!/bin/sh
/sbin/iptables-restore < /etc/iptables.up.rules

The file needs to be executable so change the permissions:

#chmod +x /etc/network/if-pre-up.d/iptables
#/usr/sbin/iptables -L
Chain INPUT (policy DROP)
target prot opt source destination
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
ACCEPT icmp -- anywhere anywhere icmp echo-request
DROP tcp -- anywhere anywhere tcp flags:FIN,SYN,RST,PSH,ACK,URG/NONE
DROP tcp -- anywhere anywhere tcp flags:!FIN,SYN,RST,ACK/SYN state NEW
DROP tcp -- anywhere anywhere tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,SYN,RST,PSH,ACK,URG
ACCEPT all -- anywhere anywhere
ACCEPT tcp -- anywhere anywhere tcp dpt:http
ACCEPT tcp -- anywhere anywhere tcp dpt:https
ACCEPT tcp -- anywhere anywhere tcp dpt:ftp
ACCEPT tcp -- anywhere anywhere tcp dpt:smtp
ACCEPT tcp -- anywhere anywhere tcp dpt:urd
ACCEPT tcp -- anywhere anywhere tcp dpt:pop3
ACCEPT tcp -- anywhere anywhere tcp dpt:pop3s
ACCEPT tcp -- anywhere anywhere tcp dpt:imap2
ACCEPT tcp -- anywhere anywhere tcp dpt:imaps
ACCEPT tcp -- anywhere anywhere tcp dpt:ssh

Debian 10 IPtables persistent make your iptables rules persistent install iptables-persistent package:

#apt-get install iptables-persistent

Debian 10 IPtables Save to update iptables with new rules use IPtables Save

# iptables-save > /etc/iptables/rules.v4
# ip6tables-save > /etc/iptables/rules.v6

Debian 10 Restore to restore iptables configuration form iptables

# iptables-restore < /etc/iptables/rules.v4

Error apt-get update upgrade Debian 8 Release file expired

$sudo apt-get update

E: Release file for http://cloudfront.debian.net/debian/dists/jessie-backports/InRelease is expired (invalid since 487d 11h 2min 2s). Updates for this repository will not be applied

Solutions

Add this to the command:

-o Acquire::Check-Valid-Until=false

For example:

sudo apt-get -o Acquire::Check-Valid-Until=false update
sudo apt-get -o Acquire::Check-Valid-Until=false dist-upgrade

then

apt-get install -y software-properties-common
apt-get install apache2
apt-get install php5.6
apt-get install php5.6-cli php5.6-common php5.6-curl php5.6-mbstring php5.6-mysql php5.6-xml php5.6-gd
apt-get install mariadb-server
iptables -L
/sbin/iptables -F && /sbin/iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP && /sbin/iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP && /sbin/iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP && /sbin/iptables -I INPUT -p icmp -m icmp --icmp-type echo-request -j ACCEPT && /sbin/iptables -A INPUT -i lo -j ACCEPT && /sbin/iptables -A OUTPUT -o lo -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 21 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 25 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 465 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 110 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 995 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 143 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 993 -j ACCEPT && /sbin/iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT && /sbin/iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT && /sbin/iptables -P OUTPUT ACCEPT && /sbin/iptables -P INPUT DROP

iptables -L

apt-get install iptables-persistent

Sudo user in Debian

Install the “sudo” Command
You need to run this command as root user:

user@debian:~$ su -
Password:
root@debian:~ # apt-get install sudo

Create a new user account.

#/usr/sbin/adduser admin

Add the user to the sudo group; By default on Debian systems, members of the group sudo are granted with sudo access. To add a user to the sudo group use the usermod command:

#usermod -aG sudo admin

Check the sudo access

#id admin
uid=1001(admin) gid=1001(admin) groups=1001(admin),27(sudo)

The user admin a member of sudo group now and to work as a root, every command must start with sudo (sudo reboot, sudo vim, sudo del, sudo mkdir, sudo……)

Error and solutions

admin@debian9:~$ sudo ifconfig
sudo: unable to resolve host (none)

Solutions

Insert hostname to /etc/hostname and /etc/hosts something like:

127.0.0.1    localhost.localdomain localhost
127.0.1.1    debian9

Disable IPv6 Debian 8

Disable IPv6 Debian 8 / Ubuntu

If can’t remove IPv6 on Debain 8 from hosting admin menu, It can disable through terminal

Debian-based/Ubuntu

sudo bash -c 'cat <<EOF >> /etc/sysctl.conf
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
EOF'

Configure SSH daemon to only listen over IPv4 by running the following:

echo 'AddressFamily inet' | sudo tee -a /etc/ssh/sshd_config

Then Reboot #reboot

SSL test on Qualys SSL Labs Rating A Configuration

Minimal Debian * Jessie and Apache V 2.4.10

Fix DNS CAA No to Yes by add CAA record on DNS Server

Clouddns: Add CAA Record, select the Provider (If available : Comodo, Digicert, etc), if manual insert field Answer with 0 (Number 0 -255), Tag with issue and Value with comodoca.com (if Comodo SSL),, letsencrypt.org (If Lets Encrypt SLL) then Save All Changes, wait 1 hour to complete.  Then check CAA status at https://caatest.co.uk

Incorrect SNI alerts

Insert below within section VirtualHost conf then #service apache2 restart

#vim /etc/apache2/sites-available/default-ssl.conf

Insert at the bottom before closed tag of the VirtualHost “</VirtualHost>”

ServerName example.com
ServerAlias www.example.com example.com

Enable Apache OCSPStapling

Specify cached response location (outside <VirtualHost>, before <VirtualHost _default_:443>

SSLStaplingCache shmcb:${APACHE_RUN_DIR}/ssl_stapling(32768)

The placed must before the following text:

## SSL Virtual Host Context
<VirtualHost _default_:443>

**** Optional Activate HTTP/2 protocol on default-ssl.conf

Insert Protocols h2 h2c http/1.1 after <VirtualHost _default_:443> on /etc/apache2/sites-available/default-ssl.conf

Below the configuration on /etc/apache2/sites-enable/default-ssl.conf

** activate Header first in with command #a2enmod headers

SSLEngine on

SSLCipherSUite "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH EDH+aRSA !CAMELLIA !SEED !3DES !RC4 !aNULL !eNULL !LOW !MD5 !EXP !PSK !SRP !DSS"

# This TLSv1.2 only
SSLProtocol TLSv1.2
# To use TLSv1.2 and TLSv1.3 uncomment line below and comment one above. Please read note above.
#SSLProtocol +TLSv1.2 +TLSv1.3

#enable of OCSP stapling, only in httpd 2.3.3 and later
SSLUseStapling on
SSLStaplingResponderTimeout 5
SSLStaplingReturnResponderErrors off

#if you want to add DHE (Diffie-Hellman key exchange), HTTPD 2.4.8 later, run openssl dhparam -out /etc/ssl/certs/dhparam.pem 4096 uncomment below
#SSLOpenSSLConfCmd Curves secp384r1
#SSLOpenSSLConfCmd DHParameters "/etc/ssl/certs/dhparam.pem"

SSLCertificateFile /etc/apache2/ssl/example.com.crt
SSLCertificateKeyFile /etc/apache2/ssl/example.com.key
SSLCertificateChainFile /etc/apache2/ssl/example.com.ca-bundle

#Header always set Strict-Transport-Security "max-age=15552000; includeSubDomains" activate first in with command #a2enmod headers
Header always set Strict-Transport-Security "max-age=15552000; includeSubDomains; preload"

Do not forget to comment (add #) for 2 lines below

#SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
#SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key

Enable and load mod_rewrite Apache2 on Debian 8

#/usr/sbin/a2enmod rewrite

Enable Headers

#/usr/sbin/a2enmod headers

Enable SSL

#/usr/sbin/a2enmod ssl

** Optional to Activate HTTP/2 module 

#/usr/sbin/a2enmod http2

Apply SSL Module to Site

#/usr/sbin/a2ensite default-ssl

To activate the new configuration, you need to run:

#service apache2 reload

Other SSL / TLS Settings on /etc/apache2/mods-enabled/ssl.conf

#Turn of SSL Compression & Ensure Ciphers are used in order

SSLCompression off
SSLHonorCipherOrder on

Enable SSL log by add script below the ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog 

ErrorLog ${APACHE_LOG_DIR}/ssl_engine.log
LogLevel debug

Sometimes error occurred, example log below

[Mon Nov 25 09:54:07.361518 2019] [ssl:error] [pid 5035] (70007)The timeout specified has expired: [client 84.240.234.36:32844] AH01985: error reading response from OCSP server

Solution

SSLStaplingResponderTimeout 3

When Sectigo’s OCSP Responder servers did not respond fast enough, the OSCP requests failed and the errors noted on this thread were logged to the Apache error log. Disable OCSP Stapling:

SSLUseStapling off

Or, instead of disabling OCSP Stapling, we could increase the default timeout value (11 seconds appeared to be suitable for yesterday’s issue):

SSLStaplingResponderTimeout 11

Upgrade Debian 7 Wheezy to Debian 8 Jessie

Backup the configuration and data first

Check current release

#sudo cat /etc/*release
PRETTY_NAME="Debian GNU/Linux 7 (wheezy)"
NAME="Debian GNU/Linux"
VERSION_ID="7"
VERSION="7 (wheezy)"
ID=debian
ANSI_COLOR="1;31"
HOME_URL="http://www.debian.org/"
SUPPORT_URL="http://www.debian.org/support/"
BUG_REPORT_URL="http://bugs.debian.org/"

Configuration files in the /etc directory

#tar -pczf etc.tar.gz --absolute-names /etc

Backup of the /var/www website directory.

#tar -pczf www.tar.gz --absolute-names /var/www

Backup of the /home directories.

#tar -pczf home.tar.gz --absolute-names /home

For ISPConfig 3 users: Backup of your email server files.

#tar -pczf vmail.tar.gz --absolute-names /var/vmail

Backup MySQL databases

#mysqldump --defaults-file=/etc/mysql/debian.cnf -cCeQ --hex-blob --quote-names --routines --events --triggers --all-databases -r all_databases.sql

Then move the tar.gz and .sql files for safe storage on a backup drive.

Check the apt sources.list file

Before upgrade to Jessie, all available Wheezy must updates first. On some systems the package source is defined as “stable” in the sources.list file instead of “wheezy” or “jessie”. To avoid an accidental early upgrade to Jessie, please check the sources.list now and ensure that it contains “wheezy” and not “stable” as source:

#nano /etc/apt/sources.list

deb http://ftp.us.debian.org/debian wheezy main contrib non-free
deb-src http://ftp.us.debian.org/debian wheezy main contrib non-free
deb http://ftp.us.debian.org/debian wheezy-updates main contrib non-free
deb http://ftp.us.debian.org/debian-security wheezy/updates main contrib non-free
#apt-get update -y && apt-get upgrade -y && apt-get dist-upgrade -y

Update the sources.list for Jessie

Edit the /etc/apt/sources.list file again:

#nano /etc/apt/sources.list

and replace its content with the following lines:

deb http://ftp.us.debian.org/debian/ jessie main contrib non-free
deb-src http://ftp.us.debian.org/debian/ jessie main contrib non-free

deb http://httpredir.debian.org/debian jessie-updates main contrib non-free
deb-src http://httpredir.debian.org/debian jessie-updates main contrib non-free

deb http://security.debian.org/ jessie/updates main contrib non-free
deb-src http://security.debian.org/ jessie/updates main contrib non-free
apt-get update -y && apt-get upgrade -y && apt-get dist-upgrade -y
reboot

To check which Debian version is currently installed on the system, take a look at the file /etc/os-release.

#cat /etc/os-release
#lsb_release -a

Extract all the tar.gz files to the folder (/var/www/html, /etc/)

#tar -xvf www.tar.gz

Move all folder and files

#mv /sourcefolder/{,.[^.]}* /destinationfolder/

Install php7 on Debian 8

Install php7 on Debian 8

sudo apt-get install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install -y php7.3

Check php version

php -v

Installing PHP 7.3 Extensions

sudo apt install php7.3-cli php7.3-fpm php7.3-json php7.3-pdo php7.3-mysql php7.3-zip php7.3-gd  php7.3-mbstring php7.3-curl php7.3-xml php7.3-bcmath php7.3-json

To install Apache Module for PHP, run:

sudo apt install libapache2-mod-php7.3

Install AWStats Web analytics on Apache2 Debian 8

AWStats is an open source Web analytics reporting tool that generates advanced web, streaming, ftp or mail server statistics, graphically. This log analyzer works as a CGI or from command line and shows you all possible information your log contains, in few graphical web pages. It uses a partial information file to be able to process large log files, often and quickly.

Update and upgrade Debian

#apt-get update && apt-get upgrade -y

Install awstats

#apt-get install awstats

enable the CGI module in Apache

#a2enmod cgi

Incase want to Disable CGI

#a2dismod cgi

Restart Apache to reflect the changes.

#/etc/init.d/apache2 restart

Configure AWStats

Create a configuration file by duplicating AWStats default conf. For example file for “vpshelpdesk.com” or ignore use default awstats.conf

#cd /etc/awstats
#cp /etc/awstats/awstats.conf /etc/awstats/vpshelpdesk.conf

Next, edit configuration file “vpshelpdesk.conf” or “awstats.conf”

#vim awstats.conf
# Examples for Apache combined logs (following two examples are equivalent):
# LogFormat = 1
# LogFormat = "%host %other %logname %time1 %methodurl %code %bytesd %refererquot %uaquot"
#
# Example for IIS:
# LogFormat = 2
#
LogFormat=1

# Change to Apache log file, by default it's /var/log/apache2/access.log
LogFile="/var/log/apache2/access.log"

# Change to the website domain name
SiteDomain="test.com"
HostAliases="www.test.com localhost 127.0.0.1"

# When this parameter is set to 1, AWStats adds a button on report page to allow to "update" statistics from a web browser
AllowToUpdateStatsFromBrowser=1

#Default DNSLookup=2, disable DNS Lookup to save memory, set to DNSLookup=0
DNSLookup=0

Build the AWStats statistics from current apache2 logs

#/usr/lib/cgi-bin/awstats.pl -config=awstats.conf -update

or if use default awstats.conf

#/usr/lib/cgi-bin/awstats.pl -config=awstats.conf -update

If it is successful no errors, some output will shown:

Create/Update database for config "/etc/awstats/awstats.conf" by AWStats version 7.2 (build 1.992)
From data in log file "/var/log/apache2/access.log"...
Phase 1 : First bypass old records, searching new record...
Searching new records from beginning of log file...
Phase 2 : Now process new records (Flush history on disk after 20000 hosts)...
Jumped lines in file: 0
Parsed lines in file: 4473
Found 0 dropped records,
Found 0 comments,
Found 0 blank records,
Found 0 corrupted records,
Found 0 old records,
Found 173 new qualified records.

Configure Apache to work with AWStats

Copy code into apache config file, recommend put at the bottom

# Directives to add to your Apache conf file to allow use of AWStats as a CGI.
# Note that path "/usr/local/awstats/" must reflect your AWStats Installation path.
#
Alias /awstatsclasses "/usr/share/awstats/lib/"
Alias /awstats-icon "/usr/share/awstats/icon/"
Alias /awstatscss "/usr/share/doc/awstats/examples/css"
#ScriptAlias /awstats/ /usr/lib/cgi-bin/
# for Security, comment code above, add code below and change folder name 
ScriptAlias /vps/ /usr/lib/cgi-bin/
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
#

Restart Apache to reflect the changes.

#/etc/init.d/apache2 restart
#service apache2 restart

The AWStats  can access via browser at http://domain/vps/awstats.pl

Setup Cron Job to update every night at midnight  (https://crontab.guru)

#vim /etc/crontab

Put code below at bottom

0 0 * * * root /usr/lib/cgi-bin/awstats.pl -config=awstats.conf -update

Error and Solutions once update AWStats via web browser

Error: Couldn’t open server log file “/var/log/apache2/access.log” : Permission denied

Give apache2 (www-data) permission on apache2 log file

#chown -R www-data:www-data /var/log/apache2/
#service apache2 restart

Warning: Error while storing hashfile: can’t create /var/lib/awstats/dnscachelastupdate.hash: Permission denied at (eval 5) line 1.

Warning: Failed to open for writing last update DNS Cache file “/var/lib/awstats/dnscachelastupdate.txt”: Permission denied

Give apache2 (www-data) permission on /var/lib/awstats/

#chown -R www-data:www-data /var/lib/awstats

Reset AWStats statistics to zero

Go to defaultr DirData /var/lib/awstats, delete all files awstatsMMYYYY.txt

#cd /var/lib/awstats
#rm -f awstats**

Go to default Apache2 access.log DirData, delete all files access.log.**

#cd /var/log/apache2/
#rm -f access.**
#touch access.log
#chown -R www-data:www-data /var/log/apache2/

Then Build the AWStats statistics again from apache2 logs

#/usr/lib/cgi-bin/awstats.pl -config=awstats.conf -update
/var/log/apache2# /usr/lib/cgi-bin/awstats.pl -config=awstats.conf -update
Create/Update database for config "/etc/awstats/awstats.conf" by AWStats version 7.2 (build 1.992)
From data in log file "/var/log/apache2/access.log"...
Phase 1 : First bypass old records, searching new record...
Direct access to last remembered record is out of file.
So searching it from beginning of log file...
Jumped lines in file: 0
Parsed lines in file: 0
 Found 0 dropped records,
 Found 0 comments,
 Found 0 blank records,
 Found 0 corrupted records,
 Found 0 old records,
 Found 0 new qualified records.

Install Nginx, MySQL, PHP LEMP Stack on Debian 8

Update, upgrade Debian and install Nginx

#sudo apt-get update && sudo apt-get dist-upgrade
#sudo apt-get install nginx

Configure UFW firewall to allow Nginx services

#sudo apt-get install ufw
#sudo ufw enable
#sudo ufw allow 'Nginx HTTP'
#sudo ufw allow ssh
#sudo ufw status

You should see allowed services (Nginx, SSH, etc) in the displayed output:

Output
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
Nginx HTTP ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Nginx HTTP (v6) ALLOW Anywhere (v6)

Test the Nginx web server on browser http://server_domain_or_IP

Install MySQL , Follow the instructions, choose Y

#sudo apt-get install mysql-server
#sudo mysql_secure_installation

Install PHP for Processing

Since Nginx does not contain native PHP processing like some other web servers, we will need to install fpm, which stands for “fastCGI process manager”. We will tell Nginx to pass PHP requests to this software for processing.  Open /etc/apt/sources.list in your text editor:

#sudo vim/etc/apt/sources.list

Append the contrib and non-free repositories at /etc/apt/sources.list

deb http://cloudfront.debian.net/debian jessie main contrib non-free
deb http://security.debian.org/ jessie/updates main contrib non-free
deb http://cloudfront.debian.net/debian jessie-updates main contrib non-free
#sudo apt-get update
#sudo apt-get install php5-fpm php5-mysql

** Choose additional PHP Extension to install as follows

#apt-get -y install php5-mysqlnd php5-curl php5-gd php5-intl php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-intl php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl

Secure PHP components

#sudo vim /etc/php5/fpm/php.ini

Uncomment cgi.fix_pathinfo and change conditions to “0”

cgi.fix_pathinfo=0

Restart our PHP processor by typing:

#sudo systemctl restart php5-fpm
#/etc/init.d/php5-fpm restart

Configure Nginx to Use the PHP Processor

Open the default Nginx server block configuration file by typing:

#sudo vim /etc/nginx/sites-available/default

Currently, with the comments removed, the Nginx default server block file looks like this:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        try_files $uri $uri/ =404;
    }
}

We need to make some changes to this file for our site.

  • First, we need to add index.php as the first value of our index directive so that files named index.php are served, if available, when a directory is requested.
  • We can modify the server_name directive to point to our server’s domain name or public IP address.
  • For the actual PHP processing, we just need to uncomment a segment of the file that handles PHP requests. This will be the location ~\.php$ location block, the included fastcgi-php.confsnippet, and the socket associated with php-fpm.
  • We will also uncomment the location block dealing with .htaccess files. Nginx doesn’t process these files. If any of these files happen to find their way into the document root, they should not be served to visitors.
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    index index.php index.html index.htm index.nginx-debian.html;

    server_name your_server_ip;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}

Test your configuration file for syntax errors by typing:

#sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

If any errors are reported, go back and recheck your file before continuing.

When ready, reload Nginx to make the necessary changes:

#sudo systemctl reload nginx

Create a PHP File phpinfo() to Test Configuration

#vim /var/www/html/info.php

Open at browser http://server_domain_or_IP/info.php