1. mod_rewrite - Allows you to match url patterns with regular expressions, and do a transparent redirect, or apply a HTTP status code response.
  2. mod_deflate - allows you to compress content before sending it to the browser using gzip compression. Browsers have supported the ability to automatically decompress the content for you. It saves lots of bandwidth (sometimes up to 70%), and decreases page download times.
  3. mod_security - a module that lets you block content based on form post data, urls, pretty much anything in the request.
  4. mod_speling - this module performs spell checking on a url. If your moving from windows to unix (case sensitive) this can save you a lot of time fixing case problems.
  5. mod_cache - a content cache keyed to URIs. You can cache in memory, or to disk.
  6. mod_setenvif - allows you to handle different environment variables, can be used to block email harvesters, referer spam, etc.
  7. mod_auth* - You can authenticate against pretty much any repository you can think of with one of the mod_auth modules, eg mod_auth_mysql, mod_auth_ldap
  8. mod_ssl - HTTPS support for Apache.
  9. mod_proxy - Turns Apache in to a Forward or Reverse proxy server.
  10. mod_benchmark - stores benchmark info and provides charts.

installare moduli standard:

    a2enmod deflate
    a2enmod rewrite

moduli disponibili

    a2enmod
    sudo apache2ctl -l

Mod Rewrite

<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
</IfModule>

una alternativa semplice su apache > 2.2.15

    FallbackResource /index.php

Setting the Default Page

You can set the default page of a directory to the page of your choice. For example in this code the default page is set as about.html instead of index.html

    #Serve Alternate Default Index Page
    DirectoryIndex about.html

Directory Alias

 
Alias /app "/var/www/app_folder/"
#
ErrorLog ${APACHE_LOG_DIR}/app_name.error.log
CustomLog ${APACHE_LOG_DIR}/access.log combine
 
<Directory "/var/www/app_folder/">
    Require all granted
    Order allow,deny
    Allow from all
    AllowOverride All
    DirectoryIndex index.php
    # RewriteEngine On
</Directory>

pass variables to the app by ENV

    <Directory "/var/www/app_folder/">
        SetEnv APPLICATION_ENV development
    </Directory>

Virtual Hosts

# minimal
<VirtualHost *:80>
    ServerName $name.local
 
    DocumentRoot "/var/www/$name"
    DirectoryIndex index.php
    <Directory "/var/www/$name">
    AllowOverride All
    Allow from All
    </Directory>
</VirtualHost>
 
# tipical
<VirtualHost *:80>
    ServerName $name.com
    ServerAlias www.$name.com
    DirectoryIndex index.php
 
    DocumentRoot "/var/www/vhosts/$name.com/"
    <Directory "/var/www/vhosts/$name.com/">
    AllowOverride All
    Allow from All
    </Directory>
 
    CustomLog /var/log/apache2/www.$name.com-access.log combined
    ErrorLog /var/log/apache2/www.$name.com-error.log
 
</VirtualHost>
 
# HTTPS
<VirtualHost *:443>
  ServerName www.$name.com
  DocumentRoot /var/www/www.$name.com/htdocs
 
  CustomLog /var/log/apache/www.$name.com-access.log combined
  ErrorLog /var/log/apache/www.$name.com-error.log
 
  # Example SSL configuration
  SSLEngine on
  SSLProtocol all -SSLv2
  SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5
  SSLCertificateFile "/var/www/www.$name.com/ssl/server.crt"
  SSLCertificateKeyFile "/var/www/www.$name.com/ssl/server.key"
</VirtualHost>

HTTPS

guida https://library.linode.com/web-servers/apache/ssl-guides/ubuntu-12.04-precise-pangolin lista Certificate authority Mozilla Generazione del certificato e Abilitazione di SSL HTTPS

essendo selfsigned compare un messaggio di warning ad ogni accesso al portale (basterà accettare il certificato, considerato inaffidabile dal browser).

sudo a2enmod ssl
 
# genera il certificato, valido n days
sudo mkdir /etc/apache2/ssl
sudo openssl req -new -x509 -days 3650 -nodes -out /etc/apache2/ssl/apache.pem -keyout /etc/apache2/ssl/apache.key
 
sudo vi /etc/apache2/ports.conf
# Listen 443
 
sudo vi /etc/apache2/sites-available/$prjname.conf
sudo service apache2 restart

assicurarsi che apache sia settato per ascoltare su porta 443

vi /etc/apache2/ports.conf
    Listen 443

A questo punto bisognera modificare il file

/etc/apache2/sites-available/ssl

modificare il VirtualHost interessato inserrendo la posizione del certificato e l'attivazione dell'engine ssl;

<VirtualHost vh_name:443>
    SSLEngine On
    SSLCertificateFile /etc/apache2/ssl/apache.pem
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key
 
    # some workarounds
    <FilesMatch "\.(html|phtml|php)$">
                    SSLOptions +StdEnvVars
    </FilesMatch>
    BrowserMatch "MSIE [2-6]" \
                    nokeepalive ssl-unclean-shutdown \
                    downgrade-1.0 force-response-1.0
    BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
 
    # virtual host configuration as usual
</VirtualHost>

Riavviare Apache e accedere in https

- Una volta ricevuto il certificato SSL via e-mail, questo dovrà essere copiato e incollato in un file di testo (con Notepad o Wordpad). Salvare il file in formato .crt. (Includere i tag -BEGIN CERTIFICATE- e -END CERTIFICATE-). - Scaricare il certificato intermedio. Copiare ed incollare il contenuto in un file di testo in formato .crt. - Copiare entrambi i file nella directory del server in cui si trovano il certificato e le chiavi. Renderli leggibili solo da root. - Cercare il file di configurazione Apache (varia da server a server, ma di solito si trova in /etc/httpd). Il nome di questo file é di norma httpd.conf. - Cercare i blocchi in httpd.conf. Per rendere il sito accessibile sia tramite https che http sarà necessario disporre di un host virtuale per ogni tipo di connessione. Creare una copiare dell`host virtuale non protetto e configurarla per l`SSL. Se invece si desidera impostare il server solo per connessioni sicure, bisognerà configurare l`attuale host virtuale. - Configurare il blocco per il sito abilitato da SSL.

    <VirtualHost 192.168.0.1:443>
        DocumentRoot /var/www/html2
        ServerName www.miodominio.com
        SSLEngine on
        SSLCertificateFile /path/to/your_domain_name.crt
        SSLCertificateKeyFile /path/to/your_private.key
        SSLCertificateChainFile /path/to/intermediate_certificate.crt
    </VirtualHost>

- Testare la configurazione Apache prima di prima di riavviare con il comandoapachectl configtest. - Riavviare Apache. - Se Apache con SSL abilitati non si dovesse riavviare, provare il comando "apachectl startssl". in tal caso configurare il normale avvio di apache con supporto ssl

HTTPS & Letsencrypt

sudo apt-get install python-letsencrypt-apache
sudo letsencrypt --apache
 
# recommended running it twice per day
sudo letsencrypt renew --dry-run --agree-tos
 
0 23 * * * root   letsencrypt renew

Prevent Hotlinking

Tired of people using your bandwidth by putting the images hosted on your server on their website? Add the following code at the bottom of your .htaccess file to prevent hotlinking.

    Options +FollowSymlinks
    #Protect against hotlinking
    RewriteEngine On
    RewriteCond %{HTTP_REFERER} !^$
    RewriteCond %{HTTP_REFERER} !^http://(www.)?example.com/ [nc]
    RewriteRule .*.(gif|jpg|png)$ http://example.com/img/stop_stealing_bandwidth.gif[nc]

Block All Requests From User Agents

It's possible to block all unwanted user agents that might be potentially harmful or perhaps just to keep the server load as low as possible.

    #Block bad bots
    SetEnvIfNoCase user-Agent ^FrontPage [NC,OR]
    SetEnvIfNoCase user-Agent ^Java.* [NC,OR]
    SetEnvIfNoCase user-Agent ^Microsoft.URL [NC,OR]
    SetEnvIfNoCase user-Agent ^MSFrontPage [NC,OR]
    SetEnvIfNoCase user-Agent ^Offline.Explorer [NC,OR]
    SetEnvIfNoCase user-Agent ^[Ww]eb[Bb]andit [NC,OR]
    SetEnvIfNoCase user-Agent ^Zeus [NC]
    <limit get="" post="" head="">
    Order Allow,Deny
    Allow from all
    Deny from env=bad_bot
    </limit>

Redirect Everyone Except Specified IPs

If for some reason you would want to deny everyone or allow only a specific group of IP addresses to access your website, add the following code to your .htaccess file: view sourceprint?

    ErrorDocument 403 http://www.example.com
    Order deny,allow
    Deny from all
    Allow from 124.34.48.165
    Allow from 102.54.68.123

SEO Friendly 301 Redirects

If you've transferred domain names or wish to redirect a specific page or pages without getting penalty from search engines such as Google, use the following code:

    Redirect 301 /d/file.html http://www.example.com/r/file.html
    <VirtualHost *:80>
      ServerName  www.servername.com
      RedirectMatch permanent ^/(.*) http://servername.com/$1
    </VirtualHost>
    #Redirect from an old domain to a new domain
    RewriteEngine On
    RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

google redirects

Disable Display of Download Request

Usually when downloading something from a web site, you'll be prompted if you wish to open the file or save it on your hard-disk. To prevent the server from prompting users wether they wish to open or save the file and to just save the file, use the following code: view sourceprint?

    AddType application/octet-stream .pdf
    AddType application/octet-stream .zip
    AddType application/octet-stream .mov

Correggere il download dei file binary

assicurarsi di caricare i file binary con il tipo di trasferimento FTP appropriato

    <Files *.pdf>
      ForceType application/octet-stream
      Header set Content-Disposition attachment
    </Files>
    <Files *.zip>
      ForceType application/octet-stream
      Header set Content-Disposition attachment
    </Files>

2.2 permissions

la v 2.2 non permette di definire VH fuori da /var/www a meno di non specificare esplicitamente nella conf della dir

  <directory /mypath>
  Require all granted
  </directory>

memory usage/var passing php

You want to communicate from PHP to other parts of the Apache request process. This includes setting variables in the access_log.

// get value
$session apache_note('session');
// set value
apache_note('session'$session);

Use apache_note( ) in combination with the logging module to write the session ID directly to the access_log for each request:

// retrieve the session ID and add it to Apache's notes table
apache_note('session_id'session_id( ));


//Then, modify your httpd.conf file to add this string to your LogFormat:

%{session_id}n

The trailing n tells Apache to use a variable stored in its notes table by another module.

If PHP is built with the --enable-memory-limit configuration option, it stores the peak memory usage of each request in a note called mod_php_memory_usage. Add the memory usage information to a LogFormat with:

%{mod_php_memory_usage}n