Apache

From Alessandro's Wiki
Revision as of 15:29, 9 December 2015 by Xunil (talk | contribs) (→‎Proxy)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
  • Potente server web multipiattaforma

Configuration

Set a ServerName!

PHP options (in .htaccess file)

  • php_valueexpose_php = On
  • php_valueerror_reporting = E_ALL|E_STRICT
  • php_valuehtml_errors = Off
  • php_valuedisplay_errors = On
  • php_valuedisplay_startup_errors = On
  • php_valuelog_errors = On
  • php_valuelog_errors_max_len = 19024
  • report_memleaks = On
  • error_log = /home/users/web/bEXAMPLE/pow.USERNAME/php_error.log
  • php_valueregister_globals = Off
  • php_valueregister_long_arrays = Off
  • php_valueregister_argc_argv = Off
  • php_value memory_limit 1024M
  • php_value post_max_size "40M"
  • php_value upload_max_filesize "40M"


  • .htaccess:show errors
php_flag display_startup_errors on 
php_flag display_errors on 
php_flag html_errors on
php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log

Bandwidth

tar zxvf mod_bw-0.7.tgz
cd mod_bw
apxs2 -i -a -c mod_bw.c

Named virtual host template

  • check before the upper configuration defining which type of virtual host you wanna use:
    • this will go into /etc/apache2/vhosts.d/00_default_vhost.conf in Gentoo
Listen *:80
NameVirtualHost *:80
<VirtualHost *:80>
       ServerAdmin staff@server.com
        ServerName      server.com
        DocumentRoot /var/www/server.com/public_html
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/server.com/public_html >
                Options FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>
</VirtualHost>

Virtual host redirect

* if you want to have the http://yoursite redirected to the www.yoursite, you can use this VH template:
<VirtualHost *:80>
        ServerName alessandrodelgallo.org
        ServerAlias blog.alessandrodelgallo.org
        Redirect permanent / http://www.alessandrodelgallo.org/
</VirtualHost>
  • or if you don't want to (or you can't) change the Apache settings, use this html code"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<meta HTTP-EQUIV="REFRESH" content="0; url=http://webiste.to.redirect.to">
</html> 

logs

  • modify the log amaunt and files:
    • log levels: debug,info,notice,warn,error,crit,alert,emerg
        LogLevel warn
        CustomLog  /var/www/SERVER_NAME/logs/access.log combined
        ErrorLog   /var/www/SERVER_NAME/logs/error.log
        RewriteLog /var/www/SERVER_NAME/logs/rewrite.log

autentication

  • standard "one-file-all-users" configuration
       AuthType Basic
       AuthName "Private Area"
       AuthUserFile /etc/apache2/passwords 
       Require valid-user
  • protect only some files using regular expressions (with character ~)
        <Location ~ "/html/(friends|messages).html" >
       AuthType Basic
       AuthName "My private files"
       AuthUserFile /usr/local/apache/passwd/passwords
       Require valid-user
        </Location>
  • use group support (in my case for subversion):
        AuthGroupFile /usr/local/apache/passwd/.htgroup
        AuthUserFile /usr/local/apache/passwd/svnusers
        <LimitExcept GET PROPFIND OPTIONS REPORT>
                Require group subversion
        </LimitExcept>

force far expire

ExpiresActive On
ExpiresDefault "access plus 1 year"

gzip compression

# add gzip compression / alessandro
 # Insert filter
 SetOutputFilter DEFLATE
 # Netscape 4.x has some problems...
 BrowserMatch ^Mozilla/4 gzip-only-text/html
 # Netscape 4.06-4.08 have some more problems
 BrowserMatch ^Mozilla/4\.0[678] no-gzip
 # MSIE masquerades as Netscape, but it is fine
 BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
 # Don't compress images
 SetEnvIfNoCase Request_URI \
 \.(?:gif|jpe?g|png)$ no-gzip dont-vary
 # Make sure proxies don't deliver the wrong content
 # Header append Vary User-Agent env=!dont-vary

Cgi

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

charset

AddDefaultCharset UTF-8

URL Rewrite

  • RewriteEngine on
  • RewriteRule ^old\.html$ new.html
  • RewriteRule ^old\.html$ new.html [R]
  • RewriteRule ^clip/([0-9][0-9])/$ /clip.php?id=$1
  • RewriteRule ^css(/)?$ /stylesheets/ [R]
  • the following were used to patch a Plone freezed website
RewriteEngine On
#RewriteLogLevel 5
# search rewrites
RewriteCond %{QUERY_STRING} ^SearchableText=([^&]+)$ [NC]
RewriteRule .* http://www.google.com/search?q=site:www.the-third-eye.org\ %1 [L,QSA]
# contgent rewirtes
RewriteRule ^concepts/ /concepts/view%3fset_language=en
RewriteRule ^(.+).jpg/$ /$1.jpg/view
RewriteRule ^(.+).png/$ /$1.png/view
RewriteRule ^(.+).JPG/$ /$1/view
RewriteRule ^(.+).jpg.1$ /$1.jpg/view
Flag and syntax 	Function
B 	Escape non-alphanumeric characters before applying the transformation. details ...
chain|C 	Rule is chained to the following rule. If the rule fails, the rule(s) chained to it will be skipped. details ...
cookie|CO=NAME:VAL 	Sets a cookie in the client browser. Full syntax is: CO=NAME:VAL:domain[:lifetime[:path[:secure[:httponly]]]] details ...
discardpath|DPI 	Causes the PATH_INFO portion of the rewritten URI to be discarded. details ...
env|E=[!]VAR[:VAL] 	Causes an environment variable VAR to be set (to the value VAL if provided). The form !VAR causes the environment variable VAR to be unset.details ...
forbidden|F 	Returns a 403 FORBIDDEN response to the client browser. details ...
gone|G 	Returns a 410 GONE response to the client browser. details ...
Handler|H=Content-handler 	Causes the resulting URI to be sent to the specified Content-handler for processing. details ...
last|L 	Stop the rewriting process immediately and don t apply any more rules. Especially note caveats for per-directory and .htaccess context (see also the END flag). details ...
next|N 	Re-run the rewriting process, starting again with the first rule, using the result of the ruleset so far as a starting point. details ...
nocase|NC 	Makes the pattern comparison case-insensitive. details ...
noescape|NE 	Prevent mod_rewrite from applying hexcode escaping of special characters in the result of the rewrite. details ...
nosubreq|NS 	Causes a rule to be skipped if the current request is an internal sub-request. details ...
proxy|P 	Force the substitution URL to be internally sent as a proxy request. details ...
passthrough|PT 	Forces the resulting URI to be passed back to the URL mapping engine for processing of other URI-to-filename translators, such as Alias or Redirect. details ...
qsappend|QSA 	Appends any query string from the original request URL to any query string created in the rewrite target.details ...
redirect|R[=code] 	Forces an external redirect, optionally with the specified HTTP status code. details ...
skip|S=num 	Tells the rewriting engine to skip the next num rules if the current rule matches. details ...
type|T=MIME-type 	Force the MIME-type of the target file to be the specified type. details ...

Direcoty Indexes

Per ingrandire la colonna del nome del file:

IndexOptions NameWidth=*

Aggiungere un alias per esportare una directory non nella root www:

Alias /_bin "/ciao/_linux_bin/"
<Directory "/ciao/_linux_bin/">
 Options Indexes MultiViews
 AllowOverride None
 Order allow,deny
 Allow from all
</Directory>

IP filters

  • Allow
Allow from 192. 
  • Deny
Deny from host.domain.com
Deny from 192.168.0.44
  • check behavior
Order deny,allow
Deny from all

SVN (mod_dav_svn)

<Location /svn/repos>
      DAV svn
      SVNPath /var/svn/repos
      AuthType Basic
      AuthName "Subversion repository"
      AuthUserFile /var/svn/conf/svnusers
      Require valid-user
</Location>
usermod -a -G svnusers apache
APACHE2_OPTS="${APACHE2_OPTS} -D SVN -D SVN_AUTHZ -D DAV -D DAV_FS"
htpasswd2 -c /usr/local/apache/passwd/svnusers user1
htpasswd2 /usr/local/apache/passwd/svnusers user2

SSL VirtualHost

  • using Gentoo distribution.
  1. enable ssl use flag for apache package
  2. edit default virtual host for a listening interface and port:
"Listen [::]:443" 
or "Listen 0.0.0.0:443"
or Listen 192.168.82.82:443
  1. we want name based virtual hosts
NameVirtualHost *:443
  • sisable compression for security reason
SSLCompression off
<VirtualHost *:443>
        # Server setup, logging + ssl
        ServerName mybox
        ServerAlias mybox
        CustomLog /var/log/apache2/mybox.access.log combined
        ErrorLog /var/log/apache2/mybox.error.log
        SSLEngine on
        SSLCertificateFile /etc/apache2/ssl/apache.pem

        # Setup .htaccess for the root of the site
        <Location />
                AuthType Basic
                AuthName "mybox"
                AuthUserFile /etc/apache2/passwords
                Require valid-user
        </Location>

        # Hudson setup - reverse proxy to hook up mybox/hudson to the localhost:8080/hudson
        SSLProxyEngine  On
        SSLProxyMachineCertificateFile /etc/apache2/ssl/apache.pem
        ProxyPass        /hudson  https://localhost:8080/hudson
        ProxyPassReverse /hudson  https://localhost:8080/hudson
        ProxyRequests    Off

        <Proxy https://localhost:8080/hudson*>
                Order deny,allow
                Allow from all
        </Proxy>

        # SVN config
        <Location /svn>
                DAV svn
                SVNParentPath /var/svn/
                SVNListParentPath On
        </Location>

        # Trac config
        Alias /trac/ /usr/share/pyshared/trac/htdocs
        <Directory "/usr/share/pyshared/trac/htdocs/">
                Options Indexes MultiViews
                AllowOverride None
                Order allow,deny
                Allow from all
        </Directory>

        <Location /trac>
                SetHandler mod_python
                PythonHandler trac.web.modpython_frontend
                PythonInterpreter main_interpreter
                PythonOption TracEnvParentDir /var/trac/
                PythonOption TracEnvIndexTemplate /var/trac/available_projects_template.html
                PythonOption TracUriRoot /trac
        </Location>

</VirtualHost>

Generating certificate

  • replace the "server" name with your domain name of your website.
SRVname=server
cd /etc/ssl/apache2
openssl genrsa 2048 > $SRVname.key
openssl req -new -x509 -nodes -sha1 -days 365 -key $SRVname.key > $SRVname.crt
  • Repeat the last step as many virtual hosts you have to serve under an ssl connection, remember to change the SRVname variable in the code:


Virtual host configuration

  • example of a basic ssl virtual host:

<VirtualHost *:80>
        ServerName mysslvirtualhost.example.com
        ServerAlias mysslvirtualhost
        Redirect permanent / https://mysslvirtualhost.example.com/
</VirtualHost>

<VirtualHost *:443>

        DirectoryIndex index.php

# SSL 
        SSLEngine on
        SSLCertificateFile /etc/ssl/apache2/server.crt
        SSLCertificateKeyFile /etc/ssl/apache2/server.key

        ServerName mysslvirtualhost.example.com
        ServerAlias mysslvirtualhost

        SSLOptions StrictRequire
        SSLProtocol all -SSLv2
#
        DocumentRoot "/var/www/mysslvirtualhost/htdocs"
        <Directory "/var/www/mysslvirtualhost/htdocs">
                SSLRequireSSL
                AllowOverride All
                Order Deny,Allow
                Allow from All
        </Directory>

 CustomLog     /var/log/apache2/mysslvirtualhost.log combined
 ErrorLog      /var/log/apache2/mysslvirtualhost_error.log
 LogLevel warn

</VirtualHost>

Cache

Cleaning the Cache

  • debug
htcacheclean -p /mnt/diskcache/ -v -t -D  -l 60M -a
  • as a deamon
htcacheclean -p /mnt/diskcache/ -t -d 5 -i -l 60M -a


Proxy

  • directives to have into httpd.conf or a virtual host configuration file
  • permissions
<Proxy *>
Order deny,allow
Deny from all
Allow from all
</Proxy>

Reverse Proxy

ProxyPass /foo http://foo.example.com/bar
ProxyPassReverse /foo http://foo.example.com/bar

Forward Proxy

ProxyRequests On
ProxyVia On

Proxy Reverse With Caching

a2enmod proxy
a2enmod proxy_http
a2enmod proxy_html
a2enmod xml2enc
a2enmod deaders
a2enmod headers
a2enmod cache
a2enmod cache_disk
a2enmod headers
a2enmod expires
a2enmod rewrite
a2enmod file_cache
apachectl configtest

Linux distribution specifics

Gentoo

  • vado diretto alla versione 2:
    • file di configurazione;
/etc/apache2/httpd.conf
  • Directory del web default:
/var/www/localhost/htdocs
  • Installarlo:
emerge -pvtD apache

controllare le USE flags che ci servono e poi

emerge apache

Fedora

  • file di configurazione;
/etc/httpd/conf/httpd.conf
  • Directori del web default:
/var/www/html/
  • Installarlo
yum install httpd