Apache – Force caching dynamic PHP content with mod_headers

Normally you want dynamic content to be fresh and not catchable. But sometimes it may be useful to cache it, like when you have website behind reverse proxy. To do this try something like this:

<filesmatch "\.(php|cgi|pl)$">
Header unset Pragma
Header unset Expires
Header set Cache-Control "max-age=3600, public"
</filesmatch>

Source:
http://www.askapache.com/htaccess/speed-up-your-site-with-caching-and-cache-control.html

Apache AuthBasic but excluding IP

Allow from IP without password prompt, and also allow from any address with password prompt

Order deny,allow
Deny from all
AuthName "htaccess password prompt"
AuthUserFile /web/askapache.com/.htpasswd
AuthType Basic
Require valid-user
Allow from 172.17.10.1
Satisfy Any

Source:
http://www.askapache.com/htaccess/apache-authentication-in-htaccess.html

Apache – precompressing static files with gzip

Some time ago I’ve show how to precompress js and css file with gzip to be available for Nginx’s mod_gzip. In default configuration Apache don’t have such module but similar functionality could be achieved with few custom rewirtes.

Basically we will start with these rewrites to serve gzipped CSS/JS files if they exist and the client accepts gzip compression:

RewriteEngine on
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.(js|css)$ $1\.$2\.gz [QSA]

Then we need to setup proper content types for such compressed files – I know how to do this in two ways:

  • pure rewrites with mod_header – witch should serve correct content type and prevent mod_deflate to gzip files that are already gzipped
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1,E=manualgzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1,E=manualgzip:1]
    
    <ifmodule mod_headers.c>
    # setup this header only if rewrites above were used
    Header set Content-Encoding "gzip" env=manualgzip
    </ifmodule>
  • by using Files clause (we could add this globally in httpd.conf)
    <files *.css.gz>
    ForceType text/css
    Header set Content-Encoding "gzip"
    </files>
    <files *.js.gz>
    #ForceType text/javascript
    # lately this one is more popular
    ForceType application/javascript
    Header set Content-Encoding "gzip"
    </files>

Both ways work fine. First one sets no-gzip variable to bypass second time compression. Second one rely on such option in my mod_deflate’s config:

SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar|gz)$ no-gzip dont-vary

which won’t compress any gz file, and this is why I have to setup Content-Encoding to gzip manually.

In both cases you will end with javacript and CSS files served from earlier prepared precomressed versions, with proper content type without engaging mod_deflate regardless you use js/css or js.gz/css.gz extension. But I strongly suggest to use extensions without gz – you will be able to disable this mechanism without any change in website code.

If you don’t know how to prepare files just look here.

P.S.
I found another similar but BAD example – it’s using AddEncoding clause to add gzip content type to ALL gzip files – this will cause problems with other compressed files with gz extension ex. tar.gz. Don’t do this. My rules above are more selective.

Source:
http://stackoverflow.com/questions/7947906/add-expiry-headers-using-apache-for-paths-which-dont-exist-in-the-filesystem
http://stackoverflow.com/questions/9076752/how-to-force-apache-to-use-manually-pre-compressed-gz-file-of-css-and-js-files

Running Apache with mod_spdy and PHP-FPM

SPDY is new protocol proposed by Google as an alternative for HTTP(S). Currently Chrome and Firefox browsers are using it as default if available on server. It is faster in most cases by few to several percent. The side effect of using mod_spdy is that it’s working well only with thread safe Apache’s modules. PHP module for Apache is not thread safe so we need to use PHP as CGI or FastCGI service. CGI is slow – so running mod_spdy for performance gain with CGI is simply pointless. FastCGI is better but it’s not possible to share APC cache in FastCGI mode (ex. using spawn-fcgi), so it’s poor too. Best for PHP is PHP-FPM which is FastCGI service with dynamic process manager and could use full advantages of APC. In such configuration I could switch from apache prefork to worker which should use less resources and be more predictable.

Installation

On Squeeze we need to install dot.deb repository – instructions are here: http://www.dotdeb.org/instructions/

Then we could install:

apt-get install apache2-mpm-worker php5-fpm libapache2-mod-fastcgi

Now, mod_spdy – packages are available here: https://developers.google.com/speed/spdy/mod_spdy/ Choose your architecture.

wget https://dl-ssl.google.com/dl/linux/direct/mod-spdy-beta_current_i386.deb
dpkg -i mod-spdy-beta_current_i386.deb

Installation of this package will add automatically a new apt repository for mod_spdy.

If you have Apache’s module for PHP still installed you should remove it (you won’t need in anymore):

apt-get purge libapache2-mod-php5

Configuring PHP-FPM

First I’m changing php-fpm default pool configuration file – edit /etc/php5/fpm/pool.d/www.conf

; I want it to listen on socket, not on port
listen = /var/run/php5-fpm/site1.socket

;uncomment to set proper permission for socket
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

;uncomment and change to - PHP leaks, so kill child after 100 requests
pm.max_requests = 100

; for proper chroot handling we will need also
php_admin_value[doc_root] = /var/www/site1
php_admin_value[cgi.fix_pathinfo] = 0

Now restart php-fpm:

service php5-fpm restart

Connecting Apache with PHP-FPM

In VirtualHost paste this:

<IfModule mod_fastcgi.c>
  Alias /php5.fcgi /var/www/site1/php5.fcgi
  FastCGIExternalServer /var/www/site1/php5.fcgi -socket /var/lib/apache2/fastcgi/site1.socket
  AddType application/x-httpd-fastphp5 .php
  Action application/x-httpd-fastphp5 /php5.fcgi

  <Directory "/var/www/site1/">
    Order deny,allow
    Deny from all
    <Files "php5.fcgi">
      Order allow,deny
      Allow from all
    </Files>
  </Directory>
</IfModule>

Enable needed modules and restart Apache:

a2enmod actions
a2enmod fastcgi
service apache2 restart

SSL

SPDY requires encrypted connection so you need configured SSL (virtualhost running on port 443). Typical configuration for SSL looks similar to this:


# some random stuff - exactly like in you NON SSL configuration :-)
SSLEngine on

SSLCertificateFile    /etc/ssl/certs/example.com.crt
SSLCertificateKeyFile /etc/ssl/private/example.com.priv.key
SSLCACertificateFile  /etc/ssl/private/ca.crt

Testing

Should work now 🙂
So, use Chromium, enter the site you just configured and then on second tab go to: chrome://net-internals/#spdy. You should see your site there if it’s running on SPDY.
You could also use plugins for Firefox or Chromium to test if site is running on SPDY.

Advertise SPDY on HTTP

When you test if SPDY is working fine (and is faster in your configuration) you could advertise availability of SPDY protocol on your HTTP VirtualHost. Thanks to that when browser supports SPDY it will use it for faster access. To do this just add header in configuration:

Header set Alternate-Protocol "443:spdy/2"

There are more options that could be used, if you need just check docs here.

Certyfikaty nazwaSSL na własnym serwerze

Od jakiegoś czasu można kupić w NetArcie certyfikaty SSL, a niedawno zrobili na nie promocję – 15zł za pierwszy rok (za certyfikat na jedną stronkę). Tzw. tanie i dobre. Po wyrobieniu certyfikatu i zapisaniu z panelu klienta mam pliczki: stonka.crt i netart_rootca.crt, które wrzucamy do Apachego, powiedzmy tak:

SSLCertificateFile /etc/ssl/certs/stonka.crt
SSLCertificateKeyFile /etc/ssl/private/priv.key
SSLCACertificateFile /etc/ssl/certs/netart_rootca.crt

Certyfikat działa w Chromie ale nie weryfikuje się w Firefoxie i Internet Explorerze. FF wyświetla błąd: sec_error_unknown_issuer – co oznacza brak certyfikatu wystawcy gdzieś w łańcuchu certyfikatów. W FAQ zero jak chodzi o konfigurację certyfikatów na serwerze poza NetArt’em…

Przeglądnąłem informacje certyfikatu rootca:

openssl x509 -in netart_rootca.crt -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            46:53:b1:a6:1e:ba:2d:c7:a3:2e:f9:39:5a:4e:f8:8c
        Signature Algorithm: sha1WithRSAEncryption
        Issuer: C=PL, O=Unizeto Technologies S.A., OU=Certum Certification Authority, CN=Certum Global Services CA
        Validity
            Not Before: Jul  6 10:31:40 2012 GMT
            Not After : Jul  4 10:31:40 2022 GMT
        Subject: C=PL, O=NetArt Sp\xC3\xB3\xC5\x82ka Akcyjna S.K.A., OU=http://nazwa.pl, CN=nazwaSSL
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
            RSA Public Key: (2048 bit)
                Modulus (2048 bit):
                    00:cc:91:f5:f7:01:09:4f:75:c8:09:c7:14:8f:e4:
                    1a:99:78:20:99:40:59:6f:10:2f:ff:fe:d0:10:ff:
                    06:a3:39:3d:c4:f1:4b:07:cf:22:39:20:80:43:50:
                    c1:af:b4:01:71:a0:a3:30:11:52:d3:d2:98:d9:c2:
                    69:f7:e3:00:d9:19:3f:3d:b3:3b:52:75:e3:d3:0c:
                    ab:ff:57:01:3a:83:5c:f5:02:bb:28:fe:90:38:8e:
                    a2:84:cf:61:48:e7:99:e0:72:24:b6:11:58:4a:18:
                    57:0d:34:18:5e:35:c8:b3:ac:04:5f:8d:38:2f:a2:
                    cf:d2:dc:74:d8:41:02:ec:e0:db:0c:54:81:a4:7a:
                    c5:34:d5:19:86:b6:1e:65:f7:3c:f6:b2:dd:3a:b5:
                    b7:91:61:18:fd:81:2c:8a:68:d7:d6:a8:33:b7:47:
                    b8:f9:48:ad:35:ee:11:93:f9:c2:a9:fa:94:8e:4f:
                    bb:d1:1e:a7:64:74:b4:f9:0f:88:a7:11:a7:33:1a:
                    c2:b1:14:0c:12:a8:6b:82:44:78:4e:d5:79:8f:5c:
                    60:29:47:4c:36:35:52:c7:ad:6c:c0:20:39:93:f1:
                    c8:b3:3b:d9:c6:ec:dd:22:45:27:a2:50:12:07:f8:
                    fe:38:79:24:89:b9:f7:de:e0:c6:e9:64:e3:f4:0b:
                    fa:c7
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints: critical
                CA:TRUE, pathlen:0
            X509v3 CRL Distribution Points: 
                URI:http://crl.certum.pl/gsca.crl

            Authority Information Access: 
                CA Issuers - URI:http://repository.certum.pl/gsca.cer

            X509v3 Authority Key Identifier: 
                keyid:45:C5:B2:86:4E:CC:DD:29:97:E4:DD:14:C4:6E:AE:4D:B8:C1:77:F8

            X509v3 Subject Key Identifier: 
                9D:CE:F0:5A:B4:CB:25:CF:36:A5:82:5D:8F:F7:7F:98:46:19:37:2E
            X509v3 Key Usage: critical
                Certificate Sign, CRL Sign
            X509v3 Certificate Policies: 
                Policy: X509v3 Any Policy
                  CPS: https://www.certum.pl/CPS

    Signature Algorithm: sha1WithRSAEncryption
        53:01:c7:87:ad:ac:d7:52:32:1f:79:5d:87:f0:01:88:8e:99:
        3f:07:d8:e4:bc:84:0a:8d:5f:d5:d5:62:c2:9b:79:33:46:f9:
        8a:d9:b2:96:ed:35:8a:29:3b:5f:38:7a:6a:70:1d:8b:84:1a:
        a3:90:81:f7:2e:60:77:78:f0:d0:84:a3:e9:8a:3c:ef:8a:34:
        6b:b1:9c:e8:e1:76:f4:87:1e:7b:3c:18:6f:98:70:2c:2a:8a:
        22:f5:ba:96:52:7e:26:62:8b:96:03:32:22:f9:80:d7:f1:dd:
        9e:c2:79:b4:17:0d:40:ff:50:6a:28:6f:e8:6f:11:8a:f9:b4:
        65:2b:52:86:31:50:c7:4d:e6:f3:be:de:6a:d1:89:90:27:61:
        6c:1c:7d:90:1f:9a:ed:02:d4:01:22:5e:8b:0b:c9:99:34:f1:
        1d:04:f4:d6:d0:71:7c:8f:0c:31:a3:2f:20:ad:35:c8:d3:b4:
        0b:38:74:89:a5:d3:55:72:e9:af:b0:b8:9f:02:c9:85:69:01:
        d8:7e:00:44:25:91:2c:5e:5b:9f:ed:52:a8:bb:5d:94:20:f4:
        c4:82:35:de:e5:d3:05:3c:14:d5:08:80:e4:74:47:e3:fa:f7:
        8c:73:40:a8:2d:ea:1f:96:c8:e3:03:2c:62:08:cc:44:02:46:
        a5:81:c2:0a

CA NetArtu nie jest domyślnie zainstalowane w żadnej przeglądarce więc nic dziwnego – ale są tam klucze Unizeto/Certum – dorzucę więc klucz CA (Chrome najwidoczniej sam potrafi to zrobić):

wget http://repository.certum.pl/gsca.cer
openssl x509 -inform der -in gsca.cer -out gsca.pem
cat gsca.pem >> netart_rootca.crt

Restart Apachego i przeglądarki już nie krzyczą. Mogliby się tylko wysilić na jakąś instrukcję albo udostępnienie od razu cabudle.crt z wszystkimi potrzebnymi certami.