Difference between revisions of "Apache 2"

(Apache 2 # redirections using mod_proxy)
 
(63 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
[[Category:Linux]]
 +
 +
 +
 
=Requirements=
 
=Requirements=
 +
 
Before going through this tutorial, I recommend you to setup:
 
Before going through this tutorial, I recommend you to setup:
 
* [[MySQL server]]
 
* [[MySQL server]]
* SSL infrastructure and create a server certificate - see [[SSL server]]
+
* [[SSL server]]
 
* [[LDAP server]]
 
* [[LDAP server]]
 +
  
  
Line 11: Line 17:
  
 
==Apache 2==
 
==Apache 2==
 +
 
This will install web server + PHP + Perl + all required libraries.
 
This will install web server + PHP + Perl + all required libraries.
  
Apache2 core
+
===Apache2 core===
<syntaxhighlight lang="bash">
 
apt-get install apache2 apache2-mpm-prefork apache2-utils ssl-cert
 
</syntaxhighlight>
 
  
Additional libraries
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
apt-get install libapache2-mod-fcgid libruby
+
apt install apache2 apache2-utils
 +
apt install ssl-cert
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Doc
+
Since Ubuntu 16.04 <code>apache2-mpm-prefork</code> is not required
<syntaxhighlight lang="bash">
 
apt-get install apache2-doc
 
</syntaxhighlight>
 
  
Perl
+
===Doc===
<syntaxhighlight lang="bash">
 
apt-get install libapache2-mod-perl2 libapache2-mod-perl2-doc
 
</syntaxhighlight>
 
  
==PHP 5==
 
Core
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
apt-get install libapache2-mod-php5 php5 php5-common
+
apt install apache2-doc
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Module PHP5
 
<syntaxhighlight lang="bash">
 
apt-get install php5-curl php5-dev php5-gd php-pear php5-imagick php5-imap php5-mcrypt
 
apt-get install php5-memcache php5-mhash php5-mysql php5-snmp php5-xmlrpc php5-xcache php5-curl php5-xsl
 
</syntaxhighlight>
 
  
Additional libs
+
===Perl===
<syntaxhighlight lang="bash">
 
apt-get install php5-cli php5-cgi php-pear php-auth php5-mcrypt mcrypt
 
</syntaxhighlight>
 
  
Image Magick
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
apt-get install php5-imagick imagemagick
+
apt-get install libapache2-mod-perl2 libapache2-mod-perl2-doc
</syntaxhighlight>
 
 
 
 
 
==Firewall==
 
You have to open the following ports:
 
* Port 80 = HTTP
 
* Port 443 = HTTPS
 
 
 
<syntaxhighlight lang="bash">
 
$IPTABLES -A INPUT -p tcp -m state -i eth0 --dport 80 -j ACCEPT
 
$IPTABLES -A INPUT -p tcp -m state -i eth0 --dport 443 -j ACCEPT
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Restart the firewall
 
<syntaxhighlight lang="bash">
 
/etc/init.d/firewall restart
 
</syntaxhighlight>
 
  
 +
===SNMP===
  
 +
Sometimes you might encounter some SNMP errors on latest Debian based distributions.
  
=PHP 5=
+
In that case you have to install a new package and run it.
  
Edit config file:
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
vim /etc/php5/apache2/php.ini
+
apt-get install snmp-mibs-downloader
 +
download-mibs
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Add / uncomment the following lines in Dynamic extensions area (~ line 865)
 
* extension=mysql.so
 
* extension=gd.so
 
  
 +
source: http://www.podciborski.co.uk/miscellaneous/snmp-cannot-find-module/
  
  
=Apache 2 configuration # Multi-threading=
+
==PHP 8==
 +
2021-11: PHP 8 is not included in Ubuntu 20.04 LTS.
  
 +
Source article: http://www.daxiongmao.eu/wiki/index.php?title=Apache_2&action=edit
  
==MPM prefork==
+
===Add PHP 8.0 repository===
This manage processes
 
* Max clients = nb of max simultaneous requests that the server can handle
 
* Server limit = max nb of process that the server can handle
 
* Start servers = nb of process to create on server start
 
* Min / Max spare servers = nb of min / max process listening for incoming request
 
* Max request per child = nb of requests that each process can execute
 
  
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
vim /etc/apache2/apache2.conf
+
apt install software-properties-common
 +
add-apt-repository ppa:ondrej/php
 +
apt update
 
</syntaxhighlight>
 
</syntaxhighlight>
Let default values; put a limit to MaxRequestsPerChild at 100 000
 
  
 +
===Install core packages===
  
==MPM worker==
+
To install the latest version of PHP:
This manage threads.
 
Threads are executed within a specific process.
 
All process’ threads share the same context and global variables.
 
  
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
vim /etc/apache2/apache2.conf
+
# PHP core
 +
apt-get install php
 +
apt-get install php-cli
 +
# Apache2 support
 +
apt install libapache2-mod-php
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Let default values; put a limit to MaxRequestsPerChild at 10 000
 
  
 +
===Modules PHP===
  
 
=Apache 2 configuration # Virtual host=
 
 
 
==Preparation==
 
Initialize configuration
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
cd /etc/apache2/sites-available/
+
apt-get install php-cgi
 +
#apt-get install php-opcache
 +
apt-get install php-gd
 +
apt-get install php-bz2
 +
apt-get install php-curl
 +
apt-get install php-xmlrpc
 +
apt-get install php-json
 +
apt-get install php-mysql
 +
apt-get install php-imap
 +
apt-get install php-mbstring
 +
# Performances
 +
apt install php-fpm libapache2-mod-fcgid
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Create target directory
+
Enable modules
<syntaxhighlight lang="bash">
 
mkdir -p /var/www/myServer
 
</syntaxhighlight>
 
  
Prepare the log files
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
mkdir -p /var/log/apache2/myServer
+
sudo a2enmod proxy_fcgi setenvif
touch /var/log/apache2/myServer/access.log
+
sudo a2enconf php8.0-fpm
touch /var/log/apache2/myServer/error.log
 
chmod -R 660 /var/log/apache2/myServer/*
 
chown -R www-data:www-data /var/log/apache2/myServer/*
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
===Utility===
  
==Configuration==
 
Init configuration
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/myServer.conf
+
apt install php-pear
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
===Configuration===
  
'''Edit configuration'''
+
Edit '''PHP config''' file:
<syntaxhighlight lang="bash">
 
vim /etc/apache2/sites-available/myServer
 
</syntaxhighlight>
 
 
 
  
To begin the virtual host, write the following lines:
 
→ Adjust the settings to your own configuration
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
<VirtualHost 192.168.0.100:80>   → Choose the best options for your needs
+
vim /etc/php/8.0/cli/php.ini
<VirtualHost *:80>
 
 
 
ServerName myServer
 
ServerAlias www.myServer *.myServer
 
ServerAdmin webmaster@domain
 
 
# Logs settings
 
LogLevel Warn
 
CustomLog {APACHE_LOG_DIR}/myServer/access.log combined
 
ErrorLog {APACHE_LOG_DIR}/myServer/error.log
 
 
 
# Root folder properties
 
DocumentRoot /var/www/myServer
 
<Directory />
 
Options FollowSymLinks
 
AllowOverride None
 
</Directory>
 
        <Directory /var/www/myServer />
 
Options Indexes FollowSymLinks MultiViews
 
AllowOverride None
 
Order allow,deny
 
allow from all
 
</Directory>
 
 
 
# Scripts CGI
 
# [ required for PHP 5 ]
 
ScriptAlias /cgi-bin/ /var/www/cgi-bin
 
<Directory "/var/www/cgi-bin">
 
AllowOverride None
 
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
 
Order allow,deny
 
Allow from all
 
</Directory>
 
 
 
</VirtualHost>
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
* Let CGI behaves like before: set <code>cgi.fix_pathinfo=1</code>
 +
* Adjust file upload size <code>upload_max_filesize = 32M</code>
 +
* Adjust post size <code>post_max_size = 32M</code>
 +
* Adjust time zone <code>date.timezone = Europe/Paris</code>
 +
* Save path: <code>session.save_path = "/tmp"</code>
  
'''Activation of a Virtual Host'''
+
===Check PHP version and configuration===
  
To activate a Virtual Host, just type
+
To ensure PHP 8.0 is well-installed just type:
<syntaxhighlight lang="bash">
 
a2ensite  myServer
 
</syntaxhighlight>
 
  
Then, restart your web server
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
/etc/init.d/apache2 restart
+
php -v
 
</syntaxhighlight>
 
</syntaxhighlight>
  
=Apache 2 configuration # SSL Virtual host=
 
  
 
+
===Image Magick===
==Create SSL certificate==
 
 
 
First of all, you need to create a server certificate.
 
Cf. SSL dedicated document → Create a new server certificate
 
 
 
>> see [[SSL server]]
 
 
 
 
 
==Enable SSL module==
 
 
 
Create symlinks for server certificate
 
  
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
ln -s /srv/ssl/certs/myServer.cert.pem /etc/apache2/webServer.pem
+
apt install php-gd php-imagick imagemagick
ln -s /srv/ssl/private/myServer.nopass.key /etc/apache2/webServer.key
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
===Configuration===
  
Activate the SSL module
+
Edit PHP config file:
  
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
a2enmod ssl
+
vim /etc/php/8.0/apache2/php.ini
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
+
Add / uncomment the following lines in Dynamic extensions area
==Prepare virtual host (optional)==
+
<syntaxhighlight lang="php">
 
+
// PHP 8  (~ line 904)
Create virtual host folder
+
extension=bz2
 
+
extension=curl
<syntaxhighlight lang="bash">
+
extension=gd
mkdir -p /var/www/myServer-ssl
+
extension=imap
cp /var/www/index.html /var/www/myServer-ssl
+
extension=mysqli
chown -R www-data:www-data /var/www/myServer-ssl
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
  
==Prepare the log files (optional)==
+
!! Note this is NOT required on Ubuntu 20.04 because these modules are enabled by default !!
  
<syntaxhighlight lang="bash">
+
==Firewall==
mkdir -p /var/log/apache2/myServer-ssl
 
touch /var/log/apache2/myServer-ssl/error.log
 
touch /var/log/apache2/myServer-ssl/access.log
 
chmod 660 /var/log/apache2/*
 
chown root:www-data /var/log/apache2/*
 
</syntaxhighlight>
 
  
 +
see [[Firewall INPUT filters#Web server]]
  
==Virtual host declaration==
+
Restart the firewall
 
 
You have 2 possibilities:
 
* Update your current virtual host
 
* Create a new one, only for the SSL virtual host
 
 
 
 
 
'''New virtual host: Init configuration'''
 
  
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
cp /etc/apache2/sites-available/default-ssl /etc/apache2/sites-available/myServer-ssl
+
/etc/init.d/firewall restart
</syntaxhighlight>
 
 
 
 
 
'''Edit V.Host configuration'''
 
 
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/sites-available/myServer-ssl
 
</syntaxhighlight>
 
 
 
 
 
Then, you will need to edit the Virtual Host configuration file:
 
 
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/sites-availables/virtualHostName
 
</syntaxhighlight>
 
 
 
!! Adjust the settings to your own configuration
 
 
 
<syntaxhighlight lang="bash">
 
# Secure web server
 
<VirtualHost _default_:443>
 
<VirtualHost 192.168.0.100:443>   → Choose the best options for your needs
 
<VirtualHost *:443>
 
 
 
ServerName myServer
 
ServerAlias www.myServer *.myServer
 
ServerAdmin webmaster@domain
 
 
# Logs settings
 
LogLevel Warn
 
CustomLog {APACHE_LOG_DIR}/myServer-ssl/access.log combined
 
ErrorLog {APACHE_LOG_DIR}/myServer-ssl/error.log
 
 
 
# Root folder properties
 
DocumentRoot /var/www/myServer-ssl
 
 
 
        # Enable SSL
 
        SSLEngine              On
 
        SSLCertificateFile      /etc/apache2/webServer.pem
 
        SSLCertificateKeyFile  /etc/apache2/webServer.key
 
 
 
        # Root directory properties
 
        <Directory /var/www/ssl />
 
            Options Indexes FollowSymLinks MultiViews
 
            AllowOverride None
 
            Order allow,deny
 
            allow from all
 
        </Directory>
 
 
 
        ##########################
 
        # ALIAS AND REDIRECTIONS #
 
        ##########################
 
 
 
</VirtualHost>
 
</syntaxhighlight>
 
 
 
Enable site
 
<syntaxhighlight lang="bash">
 
a2ensite myServer-ssl
 
</syntaxhighlight>
 
 
 
Restart the web server
 
<syntaxhighlight lang="bash">
 
/etc/init.d/apache2 restart
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==Accept auto-signed certificate==
 
Go to https://myServer/certs/
 
Cf SSL document to get installation details
 
  
=Apache 2 configuration # Redirect HTTP to HTTPS=
 
The safer way to redirect HTTP to HTTPS is use to adjust the virtual host configuration.
 
 
Edit configuration
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/sites-available/myServer
 
</syntaxhighlight>
 
  
Make it looks like:
+
==Test your installation==
<syntaxhighlight lang="bash">
 
<VirtualHost *:80>
 
ServerAdmin guillaume@qin-diaz.com
 
  
ServerName dev.daxiongmao.eu
 
ServerAlias *.dev.daxiongmao.eu dev.qin-diaz.com www.dev.qin-diaz.com
 
  
### LOG ###
+
Restart the Apache2 server
ErrorLog ${APACHE_LOG_DIR}/daxiongmao/error.log
 
LogLevel warn
 
CustomLog ${APACHE_LOG_DIR}/daxiongmao/access.log combined
 
 
## Redirect all traffic to HTTPS website
 
redirect permanent / https://myServer/
 
 
## No need of a document root anymore as everything is redirect
 
 
</VirtualHost>
 
</syntaxhighlight>
 
  
You can remove:
 
* Document root
 
* CGI url
 
* All the alias
 
 
Restart your server
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
 
service apache2 restart
 
service apache2 restart
Line 378: Line 186:
  
  
 
+
Create a simple PHP script
=Apache 2 # redirections using mod_proxy=
 
Thanks to Julien Rialland for his insight regarding this part!
 
 
 
 
 
==Principle==
 
The proxy module allow you to redirect remote user to a specific server that can be host on a different machine or port through a clear URL.
 
 
 
 
 
===Current limits===
 
Some application are not available from outside…
 
 
 
* For security reasons [default URL is not allowed]
 
 
 
[[File:Apache2 proxy security limit.png|none|Proxy for security]]
 
 
 
 
 
* Due to network issues
 
 
 
[[File:Apache2 proxy network issues.png|none|Proxy to improve network]]
 
 
 
 
 
===Proxy module role===
 
The proxy module allow you to provide access through transparent redirection.
 
 
 
It relies on:
 
* Already open port (80 or 443)
 
* Redirection rule
 
* Each service URL must be unique
 
* The target service must be reachable by the web server
 
 
 
[[File:Apache2 proxy role.png|none|Proxy role]]
 
 
 
 
 
As you can see on the following example, the previous services will be accessible using some dedicated URL.
 
Remote “http://myServer/myService” will redirect to “http://localhost:8081”
 
 
 
→ The ''mod_proxy'' is none intrusive.
 
You don’t have to change anything is the orginal service configuration. Apache2 will handle all the transformations.
 
 
 
 
 
==Proxy / redirect / rewrite==
 
When Apache2 receive a request it will be process in the following order:
 
 
 
[[File:Apache2 proxy rewrite.png|none|Proxy rewrite]]
 
 
 
 
 
So, even if you enable a full redirection to HTTPS you can still use some HTTP service through mod_proxy.
 
 
 
 
 
==Enable proxy module==
 
<syntaxhighlight lang="bash">
 
a2enmod proxy proxy_http proxy_ajp
 
</syntaxhighlight>
 
 
 
==Configure proxy redirections==
 
You have to edit / create the configuration file.
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
vim /etc/apache2/mods-enabled/proxy.conf
+
vim /var/www/html/phpinfo.php
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Adjust the file to:
+
Put the following:
<syntaxhighlight lang="bash">
+
<syntaxhighlight lang="php">
<IfModule mod_proxy.c>
+
<?php
#ProxyRequests On # Do NOT enable this
+
phpinfo();
 
+
?>
# Allow proxy for all incoming requests and users
 
<Proxy *>
 
AddDefaultCharset off
 
Order deny,allow
 
Allow from all
 
Satisfy any
 
</Proxy>
 
 
 
# Enable the handling of HTTP/1.1 "Via:" headers.
 
ProxyVia On
 
# Keep current server name in URL
 
ProxyPreserveHost On
 
 
 
# ---------------------
 
# Some proxy examples
 
# ---------------------
 
 
 
# Service JIRA is on another computer, if local network
 
ProxyPass /jira http://192.168.1.12:8080/jira
 
ProxyPassReverse /jira http://192.168.1.12:8080/jira
 
 
 
# Service ARTIFACTORY runs on a different port
 
ProxyPass /artifactory http://localhost:8081/artifactory
 
ProxyPassReverse /artifactory http://localhost:8081/artifactory
 
 
 
</IfModule>
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Some notes:
+
Adjust rights
* Do NOT put a / after the target URL
 
* Do NOT use / as ProxyPass source, use the previous redirect permanent instead
 
 
 
Apply changes and test result
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
service apache2 restart
+
chown www-data:www-data /var/www/html/phpinfo.php
 +
chmod 755 /var/www/html/phpinfo.php
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Navigate to http://myServer/artifactory
 
  
=Apache 2 configuration # LDAP authentication=
+
You can now test your installation by going to 'http://localhost/phpinfo.php' or 'http://myServer/phpinfo.php'. You should see the default page.
 
 
 
 
==Enable LDAP module==
 
<syntaxhighlight lang="bash">
 
a2enmod authnz_ldap
 
service apache2 restart
 
</syntaxhighlight>
 
 
 
 
 
==Configuration==
 
You can use the following settings inside a “.htaccess” or “VirtualHost” configuration:
 
 
 
Edit configuration
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/sites-available/myServer
 
</syntaxhighlight>
 
 
 
Adjust your virtual-host like that:
 
<syntaxhighlight lang="bash">
 
# LDAP protected directory
 
<Directory /var/www/ssl/secure>
 
  Options Indexes FollowSymLinks MultiViews
 
  AllowOverride None
 
  Order allow,deny
 
  allow from all
 
 
 
  AuthType basic
 
  AuthName "Secure area"
 
  AuthBasicProvider ldap
 
  AuthLDAPUrl "ldap://localhost:389/{LDAP ou=,dc=}?uid"
 
  Require valid-user
 
 
 
  # example
 
  # AuthLDAPBindDN "cn=admin,dc=dev,dc=daxiongmao,dc=eu"
 
  # AuthLDAPUrl "ldap://localhost:389/ou=people,dc=dev,dc=daxiongmao,dc=eu?uid"
 
 
 
</Directory>
 
</syntaxhighlight>
 
 
 
 
 
==Secure all the website==
 
You have to adjust you document root like that:
 
<syntaxhighlight lang="bash">
 
<VirtualHost _default_:443>
 
 
 
# Restrict access to document root
 
DocumentRoot /var/www/daxiongmao-ssl
 
<Directory />
 
Options FollowSymLinks
 
AllowOverride None
 
Order allow,deny
 
deny from all
 
</Directory>
 
<Directory /var/www/daxiongmao-ssl>
 
Options Indexes FollowSymLinks MultiViews
 
AllowOverride None
 
Order allow,deny
 
allow from all
 
 
AuthType basic
 
AuthName "Secure area"
 
AuthBasicProvider ldap
 
AuthLDAPUrl "ldap://localhost:389/ou=people,dc=dev,dc=daxiongmao,dc=eu?uid"
 
Require valid-user
 
</Directory>
 
[…]
 
</syntaxhighlight>
 
 
 
 
 
 
=Apache 2 configuration # Advanced configuration=
 
 
 
 
 
==Enable redirections==
 
Mod rewrite allows you to redirect source URL to another one.
 
 
 
 
 
===Enable module===
 
<syntaxhighlight lang="bash">
 
a2enmod rewrite
 
</syntaxhighlight>
 
 
 
 
 
===Alias redirection===
 
 
 
Edit configuration
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/sites-available/myServer
 
</syntaxhighlight>
 
 
 
HTTP virtual host = redirect to HTTPS
 
<syntaxhighlight lang="bash">
 
<VirtualHost *:80>
 
RewriteRule ^/myAlias(/.*|$)    https://%{HTTP_HOST}/myAlias$1 [L,R]
 
<Location /myAlias >
 
order deny,allow
 
deny from all
 
                # Only allow specific IP@
 
                # allow from 127.0.0.1 192.168.0.0/255.255.255.0
 
                allow from all
 
</Location>
 
</VirtualHost>
 
</syntaxhighlight>
 
 
 
HTTPS virtual host = service declaration
 
<syntaxhighlight lang="bash">
 
<VirtualHost _default_:443>
 
# PHPSecInfo
 
Alias /myAlias  /var/www/myAlias
 
<Location /myAlias >
 
order deny,allow
 
deny from all
 
                # Only allow specific IP@
 
                # allow from 127.0.0.1 192.168.0.0/255.255.255.0
 
                allow from all
 
        </Location>
 
</VirtualHost>
 
</syntaxhighlight>
 
 
 
Reload your configuration
 
<syntaxhighlight lang="bash">
 
/etc/init.d/apache2 reload
 
</syntaxhighlight>
 
 
 
 
 
===Redirect HTTP to HTTPS===
 
This is not the recommended method. You should use the previous method instead.
 
<syntaxhighlight lang="bash">
 
<VirtualHost *:80>
 
ServerAdmin guillaume@qin-diaz.com
 
ServerName dev.daxiongmao.eu
 
ServerAlias *.dev.daxiongmao.eu dev.qin-diaz.com www.dev.qin-diaz.com
 
 
 
### LOG ###
 
ErrorLog ${APACHE_LOG_DIR}/daxiongmao/error.log
 
LogLevel warn
 
CustomLog ${APACHE_LOG_DIR}/daxiongmao/access.log combined
 
 
## Redirect all traffic to HTTPS website
 
        RewriteEngine On
 
 
 
        # This checks to make sure the connection is not already HTTPS
 
        RewriteCond %{HTTPS} !=on
 
 
 
        # This rule will redirect users from their original location,
 
        # to the same location but using HTTPS.
 
        RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
 
 
## No need of a document root anymore as everything is redirect
 
 
</VirtualHost>
 
</syntaxhighlight>
 
 
 
 
 
===Module configuration===
 
Create the module configuration file
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/conf.d/rewrite.conf
 
</syntaxhighlight>
 
 
 
Copy / paste this configuration (adjust to your own settings!)
 
<syntaxhighlight lang="bash">
 
  RewriteEngine On
 
  # --------------------- SECURITY RULES (JOOMLA) ------------------------ #
 
  ## End of deny access to extension xml files
 
  RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]
 
  # Block out any script trying to base64_encode crap to send via URL
 
  RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
 
  # Block out any script that includes a <script> tag in URL
 
  RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
 
  # Block out any script trying to set a PHP GLOBALS variable via URL
 
  RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
 
  # Block out any script trying to modify a _REQUEST variable via URL
 
  RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
 
  # Send all blocked request to homepage with 403 Forbidden error!
 
  RewriteRule ^(.*)$ index.php [F,L]
 
  # --------------------- SECURITY RULES (PERSONAL) ------------------------ #
 
  ## DENY REQUEST BASED ON REQUEST METHOD ###
 
  RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD)$ [NC]
 
  RewriteCond %{REQUEST_METHOD} (GET|POST) [NC]
 
  RewriteRule ^.*$ - [F]
 
  # Eviter les failles de securite
 
  RewriteCond %{QUERY_STRING} ^(.*)http(\:|\%3A)(.*)$
 
  RewriteCond %{QUERY_STRING} mosConfig_ [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^(.*)(%3C|<)/?script(.*)$ [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^(.*)(%3D|=)?javascript(%3A|:)(.*)$ [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^(.*)document\.location\.href(.*)$ [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^(.*)base64_encode(.*)$ [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^(.*)GLOBALS(=|[|%[0-9A-Z]{0,2})(.*)$ [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^(.*)_REQUEST(=|[|%[0-9A-Z]{0,2})(.*)$ [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^(.*)(SELECT|INSERT|DELETE|CHAR\(|UPDATE|REPLACE|LIMIT)(.*)$
 
  # Eviter les erreurs basiques
 
  RewriteCond %{QUERY_STRING} \.\.\/    [NC,OR]
 
  RewriteCond %{QUERY_STRING} boot\.ini [NC,OR]
 
  RewriteCond %{QUERY_STRING} tag\=    [NC,OR]
 
  RewriteCond %{QUERY_STRING} ftp\:    [NC,OR]
 
  RewriteCond %{QUERY_STRING} http\:    [NC,OR]
 
  RewriteCond %{QUERY_STRING} https\:  [NC,OR]
 
  RewriteCond %{QUERY_STRING} mosConfig [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^.*(\(|\)|<|>|'|"|\?|\*).* [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^.*(%22|%27|%3C|%3D|%3E|%7B|%7C).* [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^.*(%0|%A|%B|%C|%D|%F|127\.0).* [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^.*(globals|encode|localhost|loopback).* [NC,OR]
 
  RewriteCond %{QUERY_STRING} ^.*(select|insert|union|declare|drop).* [NC]
 
  RewriteRule ^(.*)$ - [F,L]
 
 
 
  # Ban Typical Vulnerability Scanners and others
 
  # Kick out Script Kiddies
 
  RewriteCond %{HTTP_USER_AGENT} ^(java|curl|wget).* [NC,OR]
 
  RewriteCond %{HTTP_USER_AGENT} ^.*(libwww-perl|curl|wget|python|nikto|wkito|pikto|scan|acunetix).* [NC,OR]
 
  RewriteCond %{HTTP_USER_AGENT} ^.*(winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner).* [NC,OR]
 
  # Eviter les programmes de Zombies
 
  RewriteCond %{HTTP_USER_AGENT} ^Anarchie [OR]
 
  RewriteCond %{HTTP_USER_AGENT} ^ASPSeek [OR]
 
  RewriteCond %{HTTP_USER_AGENT} ^attach [OR]
 
  RewriteCond %{HTTP_USER_AGENT} ^autoemailspider [OR]
 
  RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
 
  RewriteCond %{HTTP_USER_AGENT} ^Xenu [OR]
 
  RewriteCond %{HTTP_USER_AGENT} ^Zeus.*Webster [OR]
 
  RewriteCond %{HTTP_USER_AGENT} ^Zeus
 
  RewriteRule ^.* - [F,L]
 
 
 
  # Allow the robots to reference our website
 
  RewriteCond %{HTTP_USER_AGENT} !^Googlebot [NC]
 
  RewriteCond %{HTTP_USER_AGENT} !^Googlebot-Image [NC]
 
  RewriteCond %{HTTP_USER_AGENT} !^Googlebot-Mobile [NC]
 
  RewriteCond %{HTTP_USER_AGENT} !^Msnbot [NC]
 
  RewriteCond %{HTTP_USER_AGENT} !^Mediapartners-Google [NC]
 
 
 
  # Keep request without referer
 
  RewriteCond %{HTTP_REFERER} !^$
 
 
 
  # To allow your pictures to be displayed on Google
 
  RewriteCond %{HTTP_REFERER} !^http://.*google\.(comŠ(co\.)?[a-z]{2})/
 
  # To forbid the copy of your pictures to anyone else : display an other image !
 
  RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/hotlinkis.jpg [L]
 
</syntaxhighlight>
 
 
 
 
 
===Take changes into account===
 
You have to restart the server to use this settings
 
<syntaxhighlight lang="bash">
 
service apache2 restart
 
</syntaxhighlight>
 
 
 
 
 
==Ports number==
 
You can change the Apache2 server ports
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/ports.conf
 
</syntaxhighlight>
 
 
 
Edit
 
<syntaxhighlight lang="bash">
 
# HTTP
 
Listen 80
 
# HTTPS
 
Listen 443
 
</syntaxhighlight>
 
 
 
 
 
==Restricted access==
 
Edit configuration
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/sites-available/myServer
 
</syntaxhighlight>
 
 
 
If your server is directly accessible on Internet: you should protect it!
 
<syntaxhighlight lang="bash">
 
# Disable access to the entire file system except for the directories that
 
# are explicitly allowed later.
 
#
 
<Directory />
 
        AllowOverride None
 
        Order Deny,Allow
 
        Deny from all
 
</Directory>
 
 
 
# Protect .htacess files
 
<Files ~ "^\.ht">
 
    Order allow,deny
 
    Deny from all
 
</Files>
 
</syntaxhighlight>
 
 
 
 
 
==Be discreet!==
 
Check the current server status using a simple PHP info file
 
 
 
Do not gives details about your configuration to outsiders.
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/conf.d/security
 
</syntaxhighlight>
 
 
 
Set the following settings
 
<syntaxhighlight lang="bash">
 
#### Ask your server to be more discret!
 
# ServerTokens
 
# Set to one of:  Full | OS | Minimal | Minor | Major | Prod
 
ServerTokens Prod
 
 
 
ServerSignature Off
 
TraceEnable Off
 
</syntaxhighlight>
 
 
 
Restart Apache2
 
<syntaxhighlight lang="bash">
 
service apache2 restart
 
</syntaxhighlight>
 
 
 
Re-run PHP info, you should have less information.
 
 
 
 
 
 
 
=Apache 2 and PHP5: Secure your installation!=
 
 
 
 
 
==PHP Security Info==
 
If you want to test your PHP security, you can use the PHPSecInfo tool, available at: http://phpsec.org/projects/phpsecinfo/index.html
 
 
 
 
 
===Installation===
 
<syntaxhighlight lang="bash">
 
cd /tmp
 
wget http://phpsec.org/projects/phpsecinfo/phpsecinfo.zip
 
unzip phpsecinfo.zip
 
mv phpsecinfo-Version phpsecinfo
 
mv phpsecinfo/ /var/www
 
cd /var/www
 
chown -R www-data:www-data phpsecinfo
 
</syntaxhighlight>
 
 
 
 
 
===Virtual host configuration===
 
Edit configuration
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/sites-available/myServer
 
</syntaxhighlight>
 
 
 
!! For security reason: DO NOT use 'phpsecinfo' as alias. It's too easy to guess.
 
<syntaxhighlight lang="bash">
 
<VirtualHost *:80>
 
# Advanced redirection – Only allow specific IP @
 
RewriteRule ^/phpsec(/.*|$)    https://%{HTTP_HOST}/phpsec$1 [L,R]
 
<Location /phpsec >
 
order deny,allow
 
deny from all
 
                # Only allow specific IP@
 
                # allow from 127.0.0.1 192.168.0.0/255.255.255.0
 
                allow from all
 
</Location>
 
</VirtualHost>
 
 
 
<VirtualHost _default_:443>
 
# PHPSecInfo
 
Alias /phpsec  /var/www/phpsecinfo
 
<Location /phpsec >
 
order deny,allow
 
deny from all
 
                # Only allow specific IP@
 
                # allow from 127.0.0.1 192.168.0.0/255.255.255.0
 
              allow from all
 
        </Location>
 
</VirtualHost>
 
</syntaxhighlight>
 
 
 
Reload your configuration
 
<syntaxhighlight lang="bash">
 
/etc/init.d/apache2 reload
 
</syntaxhighlight>
 
 
 
 
 
===Run the test===
 
To asset your current installation you can run the test: https:// myServer/phpsec
 
 
 
 
 
==Improve security==
 
 
 
===PHP5 sessions and temp files===
 
Create specific directory to store the sessions and temp files:
 
<syntaxhighlight lang="bash">
 
mkdir -p /etc/php5/temp
 
mkdir -p /etc/php5/session
 
chown -R www-data:root /etc/php5/temp
 
chown -R www-data:root /etc/php5/session
 
chmod -R 770 /etc/php5/session
 
chmod -R 770 /etc/php5/temp
 
</syntaxhighlight>
 
 
 
Edit the configuration file
 
<syntaxhighlight lang="bash">
 
vim /etc/php5/apache2/php.ini
 
</syntaxhighlight>
 
 
 
line 798 → upload_tmp_dir = /etc/php5/temp
 
line 1409 → session.save_path = "/etc/php5/session"
 
 
 
===PHP5 tweak===
 
<syntaxhighlight lang="bash">
 
vim /etc/php5/apache2/php.ini
 
</syntaxhighlight>
 
 
 
line 261 → expose_php = Off
 
line 480 → display_errors=Off
 
line 675 → post_max_size=256K
 
line 814 → allow_url_fopen=Off
 
 
 
DO NOT enable the open_basedir (even if the test say so! It’s a troublesome setting)
 
 
 
Restart your server to load the changes:
 
<syntaxhighlight lang="bash">
 
service apache2 restart
 
</syntaxhighlight>
 
 
 
Re-run the test. Then:
 
* Ignore the open_basedir and upload_tmp_dir alerts, if any.
 
* You can enable some specific options with a .htaccess file
 
 
 
 
 
===Change Apache 2 UID===
 
Do not change the UID if you already have install web programs such as phpldapadmin or phpmyadmin, cacti, ...
 
 
 
====Change the Apache UID====
 
<syntaxhighlight lang="bash">
 
vim /etc/group
 
</syntaxhighlight>
 
 
 
Change www-data UID
 
<syntaxhighlight lang="bash">
 
    www-data:x:10033:
 
</syntaxhighlight>
 
 
 
====Change the Apache GID====
 
<syntaxhighlight lang="bash">
 
vim /etc/passwd
 
</syntaxhighlight>
 
 
 
Change the group settings
 
<syntaxhighlight lang="bash">
 
www-data:x:10033:10033:www-data:/var/www:/bin/false
 
</syntaxhighlight>
 
 
 
Apply modifications
 
<syntaxhighlight lang="bash">
 
chown -R www-data:www-data /var/www/*
 
chown -R www-data:root /etc/php5/*
 
</syntaxhighlight>
 
 
 
To take on the modifications you have to reboot your server.
 
 
 
 
 
===Avoid DOS attacks===
 
Source: Linux mag’ – Hors serie Apache2
 
 
 
You can protect your server from Denial Of Service (DOS) attacks through mod_evasive
 
<syntaxhighlight lang="bash">
 
apt-get install libapache2-mod-evasive
 
</syntaxhighlight>
 
 
 
Prepare log directory
 
<syntaxhighlight lang="bash">
 
mkdir /var/log/apache2/mod_evasive
 
chown -R www-data:www-data  /var/log/apache2/mod_evasive
 
</syntaxhighlight>
 
 
 
Enable module
 
<syntaxhighlight lang="bash">
 
a2enmod mod-evasive
 
</syntaxhighlight>
 
 
 
 
 
===Configuration===
 
Create the configuration file
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/conf.d/mod_evasive.conf
 
</syntaxhighlight>
 
 
 
Put:
 
<syntaxhighlight lang="bash">
 
# Mod evasive configuration
 
# Based upon Linux Mag
 
<IfModule mod_evasive20.c>
 
DOSHashTableSize 3097
 
 
 
# Limit user to 5 pages per 2 seconds
 
DOSPageCount 5
 
DOSPageInterval 2
 
 
 
# No more than 100 HTTP request per second (HTML, CSS, images, …)
 
DOSSiteCount 100
 
DOSSiteInterval 1
 
 
 
# Block client for 300 seconds
 
DOSBlockingPeriod 300
 
# Send alert email
 
#DOSEmailNotify "admin@myDomain"
 
 
 
# Log directory
 
DOSLogDir "/var/log/apache2/mod_evasive"
 
 
 
# Command to execute on ban
 
#DOSSystemCommand "/sbin/iptables -I INPUT -s %s -j DROP"
 
 
 
# Ignore following IP and networks
 
DOSWhiteList 127.0.0.1
 
#DOSWhitelist 66.249.65.*
 
<IfModule mod_evasive20.c>
 
</syntaxhighlight>
 
 
 
DosHashTableSize = Size of the hash table.
 
* The greater, the more memory is required but the faster it is! The value must be a prime number
 
 
 
 
 
Apply changes
 
<syntaxhighlight lang="bash">
 
service apache2 restart
 
</syntaxhighlight>
 
 
 
 
 
 
 
=Apache2 configuration # Improve server performances=
 
 
 
==Mod deflate: improved the bandwidth==
 
 
 
To improve the bandwidth, you can compress pages and type of content.
 
 
 
=> You can improved your bandwidth from 20 to 30%.
 
 
 
 
 
To do so, you need a specific module for Apache: mod_deflate
 
<syntaxhighlight lang="bash">
 
a2enmod deflate
 
touch /var/log/apache2/deflate.log
 
chown www-data:www-data /var/log/apache2/deflate.log
 
chmod 740 /var/log/apache2/deflate.log
 
</syntaxhighlight>
 
 
 
Edit your web server configuration file:
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/conf.d/deflate.conf
 
</syntaxhighlight>
 
 
 
Add the following lines:
 
<syntaxhighlight lang="bash">
 
### Bandwidth optimization
 
<IfModule mod_deflate.c>
 
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript text/css application/x-javascript
 
DeflateFilterNote deflate_ratio
 
LogFormat "%v %h %l %u %t \"%r\" %>s %b"
 
CustomLog /var/log/apache2/deflate.log vhost_with_deflate_info
 
</IfModule>
 
</syntaxhighlight>
 
 
 
Restart your web server:
 
<syntaxhighlight lang="bash">
 
/etc/init.d/apache2 restart
 
</syntaxhighlight>
 
 
 
 
 
==Mod expires: use the cache of your clients==
 
Another way to improve performances and bandwidth: use the client's cache.
 
 
 
To do so, you need a specific module for Apache: mod_expires
 
<syntaxhighlight lang="bash">
 
a2enmod expires
 
</syntaxhighlight>
 
 
 
Edit your web server configuration file:
 
<syntaxhighlight lang="bash">
 
vim /etc/apache2/expires.conf
 
</syntaxhighlight>
 
 
 
Add the following lines
 
<syntaxhighlight lang="bash">
 
#### Client's cache settings
 
<IfModule mod_expires.c>
 
ExpiresActive on
 
# set the default to 24 hours
 
ExpiresDefault "access plus 24 hours"
 
# cache shockwave-flash for 2 weeks (days | weeks | mounths | years)
 
ExpiresByType application/x-shockwave-flash "access plus 2 weeks"
 
ExpiresByType flv-application/octet-stream "access plus 3 days"
 
# cache common graphics for 3 days
 
ExpiresByType image/jpg "access plus 2 weeks"
 
ExpiresByType image/gif "access plus 2 weeks"
 
ExpiresByType image/jpeg "access plus 2 weeks"
 
ExpiresByType image/png "access plus 2 weeks"
 
# cache CSS for 24 hours
 
ExpiresByType text/css "access plus 24 hours"
 
</IfModule>
 
</syntaxhighlight>
 
 
 
Restart your web server:
 
<syntaxhighlight lang="bash">
 
/etc/init.d/apache2 restart
 
</syntaxhighlight>
 

Latest revision as of 16:38, 3 November 2021



Requirements

Before going through this tutorial, I recommend you to setup:



Installation

Apache 2

This will install web server + PHP + Perl + all required libraries.

Apache2 core

apt install apache2 apache2-utils 
apt install ssl-cert

Since Ubuntu 16.04 apache2-mpm-prefork is not required

Doc

apt install apache2-doc


Perl

apt-get install libapache2-mod-perl2 libapache2-mod-perl2-doc


SNMP

Sometimes you might encounter some SNMP errors on latest Debian based distributions.

In that case you have to install a new package and run it.

apt-get install snmp-mibs-downloader
download-mibs


source: http://www.podciborski.co.uk/miscellaneous/snmp-cannot-find-module/


PHP 8

2021-11: PHP 8 is not included in Ubuntu 20.04 LTS.

Source article: http://www.daxiongmao.eu/wiki/index.php?title=Apache_2&action=edit

Add PHP 8.0 repository

apt install software-properties-common
add-apt-repository ppa:ondrej/php
apt update

Install core packages

To install the latest version of PHP:

# PHP core
apt-get install php
apt-get install php-cli
# Apache2 support
apt install libapache2-mod-php


Modules PHP

apt-get install php-cgi 
#apt-get install php-opcache
apt-get install php-gd 
apt-get install php-bz2 
apt-get install php-curl 
apt-get install php-xmlrpc
apt-get install php-json 
apt-get install php-mysql 
apt-get install php-imap 
apt-get install php-mbstring
# Performances
apt install php-fpm libapache2-mod-fcgid

Enable modules

sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php8.0-fpm

Utility

apt install php-pear

Configuration

Edit PHP config file:

vim /etc/php/8.0/cli/php.ini
  • Let CGI behaves like before: set cgi.fix_pathinfo=1
  • Adjust file upload size upload_max_filesize = 32M
  • Adjust post size post_max_size = 32M
  • Adjust time zone date.timezone = Europe/Paris
  • Save path: session.save_path = "/tmp"

Check PHP version and configuration

To ensure PHP 8.0 is well-installed just type:

php -v


Image Magick

apt install php-gd php-imagick imagemagick

Configuration

Edit PHP config file:

vim /etc/php/8.0/apache2/php.ini

Add / uncomment the following lines in Dynamic extensions area

// PHP 8  (~ line 904)
extension=bz2
extension=curl
extension=gd
extension=imap
extension=mysqli


!! Note this is NOT required on Ubuntu 20.04 because these modules are enabled by default !!

Firewall

see Firewall INPUT filters#Web server

Restart the firewall

/etc/init.d/firewall restart


Test your installation

Restart the Apache2 server

service apache2 restart


Create a simple PHP script

vim /var/www/html/phpinfo.php

Put the following:

<?php
phpinfo();
?>

Adjust rights

chown www-data:www-data /var/www/html/phpinfo.php
chmod 755 /var/www/html/phpinfo.php


You can now test your installation by going to 'http://localhost/phpinfo.php' or 'http://myServer/phpinfo.php'. You should see the default page.