Geody Labs

# Main Index: Debian Linux Magic Spells Cheat Sheet (one liners, how to, tips and tricks)

# Install a LAMP (Linux, Apache, MySQL, PHP) webserver

Install servers and related software

apt-get install apache2 apt-get install lynx apt-get install openssl # apt-get install php4 libapache2-mod-php4 php4-pear php4-gd php4-mcrypt # PHP 4 # apt-get install php4-mysql # MySQL support for PHP 4 # apt-get install php5 libapache2-mod-php5 php-pear php5-gd php5-mcrypt php5-sqlite # PHP 5 # apt-get install php5-mysql # MySQL support for PHP 5 # apt install php7.0 libapache2-mod-php7.0 php-pear php7.0-gd php7.0-mcrypt php7.0-mbstring php7.0-sqlite3 # PHP 7 # apt install php7.0-mysql # MySQL support for PHP 7 apt install php7.3 libapache2-mod-php7.3 php-pear php7.3-gd php7.3-mbstring php7.3-sqlite3 # PHP 7.3 apt install php-imagick # ImageMagick for PHP apt install php7.3-mysql # MySQL support for PHP 7.3 # apt-get install mysql-server # Obsolete since Debian GNU/Linux 10 (buster) apt install mariadb-server-core-10.3 mariadb-server-10.3 mariadb-plugin-tokudb mariadb-plugin-spider mariadb-plugin-oqgraph mariadb-plugin-mroonga mariadb-plugin-connect apt install phpmyadmin

Apache Webserver

Apache 2 configuration: /usr/sbin/apache2 -v # Return Apache 2 version openssl version -v # Get OpenSSL version apache2 -l # list compiled in Apache 2 modules apache2ctl -l # list compiled in Apache 2 modules apache2ctl -M # list loaded Apache 2 modules a2query -M # Return Apache Multi-Processing Module (MPM): event, prefork, worker a2enmod # Add a module choosing it from a list. You'll have to restart Apache 2 then. a2enmod rewrite # Add rewrite module. Restart Apache to enable it. jed /etc/apache2/apache2.conf If your webserver is too slow, you may have to adjust the value for MaxClients: if it's too low it will allow too few simultaneous accesses, if it's too high it will require too much resources to handle them. Try with MaxClients 50 or MaxClients 100 . <IfModule prefork.c> MaxClients 100 </IfModule> Also, you'd better set MaxKeepAliveRequests to a value higher than the default: MaxKeepAliveRequests 2000 You can also add the expires module and set expiry periods for the cache of file types you don't change often on the server (like images): <IfModule expires_module> ExpiresActive On ExpiresDefault "access plus 2 days" ExpiresByType text/php "access plus 1 second" ExpiresByType text/x-php "access plus 1 second" ExpiresByType application/php "access plus 1 second" ExpiresByType application/x-php "access plus 1 second" ExpiresByType application/x-httpd-php "access plus 1 second" ExpiresByType text/html "access plus 2 days" ExpiresByType text/plain "access plus 2 days" ExpiresByType image/jpg "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType image/gif "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType text/css "access plus 1 month" ExpiresByType application/pdf "access plus 1 month" ExpiresByType text/x-javascript "access plus 1 week" # ExpiresByType application/x-shockwave-flash "access plus 1 month" ExpiresByType image/x-icon "access plus 1 year" </IfModule> If you use .htaccess files in your web directories to have them to be executed by the web server, you must be sure that AllowOverride is set to All for such directories: <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> Specify available charsets and default charset: AddCharset ISO-8859-1 .iso8859-1 .latin1 AddCharset UTF-8 .utf8 # AddDefaultCharset UTF-8 AddDefaultCharset ISO-8859-1 jed /etc/apache2/ports.conf # Port listened by the webserver (normally 80 for HTTP connections and 443 for HTTPS secure connections) jed /etc/apache2/sites-enabled/default.conf # set DocumentRoot and create Virtual Hosts (vhosts). Older versions of Apache2 stores sites by default in /etc/apache2/sites-available/default This is an example of a VirtualHost: <VirtualHost> ServerName ServerAdmin DocumentRoot "/var/www/" ServerSignature On LogLevel Warn ErrorLog /var/log/apache2/example-com_error.log CustomLog /var/log/apache2/example-com_access.log combined </VirtualHost> Check Apache configuration for errors: apache2ctl configtest Restart Apache after modifying its configuration: /etc/init.d/apache2 restart See if Apache is running: netstat -plntu | grep apache # if you get a line containing the socket listened by the Apache webserver, then it's running See Apache error log: cat /var/log/apache2/error.log Delete Apache access and error logs rm /var/log/apache2/*.gz # Delete archived logs rm /var/log/apache2/* # In case you want to delete access and error logs for all websites. IMPORTANT: Note that you'll have to restart Apache to set up logs and have them running again


Make sure the PHP package is enabled on Apache: a2query -m php7.3 If it replies with "No module matches php7.3", then enable it: a2enmod php7.3 Then restart Apache PHP configuration on Apache 2: jed /etc/php4/apache2/php.ini # PHP 4 configuration jed /etc/php5/apache2/php.ini # PHP 5 configuration jed /etc/php/7.x/apache2/php.ini # PHP 7.x configuration (make sure to replace x with your current subversion of PHP 7 ) Make sure engine = On in the PHP configuration file or PHP will not work at all. You may want to set short_open_tag = On if your PHP code uses short tags, which means < ? ... ? > instead of < ?php ... ? > You may specify the charset (character encoding) used by PHP generated pages. Note that it overrides charsets specified in the Apache configuration or in the HTML document (such as <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" /> in HTML 4 or <meta charset="ISO-8859-1" /> in HTML 5), so you'd probably better leave it empty default_charset = "" however in case you need to set it, most popular settings are: default_charset = "UTF-8" or default_charset = "iso-8859-1" Show PHP version: php -v Show PHP info: php -i List compiled-in PHP modules: php -m To send e-mails from PHP scripts, you need to install sendmail apt-get install sendmail sendmail-bin sendmail-doc rmail Then edit the hosts file ( jed /etc/hosts ) and set the alias for the IP as DOMAIN localhost localhost.localdomain HOSTNAME where DOMAIN is a domain name (for example: ) addressed to your server's IP and HOSTNAME is the hostname of your server (that you can get with the command hostname ). The domain name is not necessary but strongly recommended because some antispam services blacklist servers which send e-mails identifying themselves (EHLO) as "localhost.localdomain". After setting the hosts file you have to reconfigure and restart sendmail: sendmailconfig # Normally you have to just reply with Y to all questions service sendmail restart To send a test e-mail from the console: echo "Subject: test"; echo "Body Test"; |/usr/lib/sendmail -v -F SENDER@MAILBOX.EXAMPLE.COM -t RECEIVER@MAILBOX.EXAMPLE.COM You should check sendmail_path in PHP configuration (php.ini) and make sure it's either disabled or set to the default value of sendmail -t -i To send an e-mail from a PHP page you have to use the mail command, like in this example: mail($emailto, $emailsubject, $emailbody, "From: ".$emailfrom."\nReply-To: ".$emailreplyto."\nX-Mailer: ".$xmailer); Of course all sample variables used must be set properly. This is a test without using variables, you need to replace email addresses in this example with actual working ones: mail('', 'Test', "This is a test\nfrom PHP", "From: ".''."\nReply-To: ".''."\nX-Mailer: ".'PHP'); Check the log of last sent e-mails: tail --lines=20 /var/log/mail.log

Upgrading PHP

Upgrading from PHP 4 to PHP 5

# Note: this will also upgrade from MySQL 4 to MySQL 5, if MySQL 4 is installed # Warning: newer versions of MySQL often use different formats for tables than earlier versions. In some cases you can attempt to make restore such tables compatible using repair table TABLE; and optimize table TABLE; You'd better dump all your tables before to upgrade, in case you'll need to restore them after. In fact you may need to DROP tables which are no longer working as expected and rebuild them. A common issue are tables containing floating point fields: queries containing comparisons based on those fields will no longer work as they used to. # stop the servers /etc/init.d/apache2 stop /etc/init.d/mysql stop # remove PHP 4 apt-get remove libapache2-mod-php4 php4 php4-gd php4-pear php4-mcrypt php4-mysql # You have to remove MySQL as well apt-get remove mysql-server # Install PHP 5 apt-get install php5 libapache2-mod-php5 php5-sqlite php-pear php5-gd php5-mcrypt # PHP 5 apt-get install php5-mysql # MySQL support for PHP 5 # Install MySQL again apt-get install mysql-server # Reinstall phpmyadmin (if you need it) apt-get install phpmyadmin # Removing PHP 4 will remove phpmyadmin as well, you'll have to reinstall it if you need it # Make sure that there are no references to PHP 4 left in the Apache configuration jed /etc/apache2/apache2.conf # Change <IfModule mod_php4.c> as <IfModule mod_php5.c> # Add .php5 to AddType application/x-httpd-php # Comment out <IfDefine HAVE_PHP4> ... </IfDefine> and everything between # restart the servers /etc/init.d/mysql restart /etc/init.d/apache2 restart

Switch from PHP 5 to PHP 7

If you have two different versions of PHP, for example PHP 5.6 and PHP 7.0, as it can happen after upgrading Debian from jessie to stretch, you can switch between them with these commands: update-alternatives --config php # Set the default PHP version for the command php (this will not influence the version used on the Apache webserver) a2dismod php5 # Dismount the Apache2 Module for PHP5 a2enmod php7.0 # Mount the Apache2 Module for PHP7 systemctl restart apache2 # Restart Apache


Show MySQL version: mysql -V See if MySQL is running: netstat -plntu | grep mysql # if you get a line containing the socket listened by the MySQL server, then it's running Set MySQL root password: $ mysql mysql> SET PASSWORD FOR root@localhost = PASSWORD('newpassword'); Create an alternate user with root-like access: $ mysql -u root -pROOT_PASSWORD mysql mysql> CREATE USER 'USER_NAME'@'localhost' IDENTIFIED BY 'SET_PASSWORD_HERE'; GRANT ALL PRIVILEGES ON *.* TO 'USER_NAME'@'localhost'; FLUSH PRIVILEGES; Create a new mysql user and assign a database to him $ mysql -u root -pROOT_PASSWORD mysql mysql> insert into user (Host, User, Password, Select_priv) values ('localhost', 'USERNAME', password('USER_PASSWORD'), 'N'); Query OK, 1 row affected (0.00 sec) mysql> insert into db (Host, Db, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Create_tmp_table_priv, Lock_tables_priv) values ('localhost', 'USER_DATABASE', 'USER_NAME', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y'); Query OK, 1 row affected (0.00 sec) mysql> quit $ mysqladmin -u root -pROOT_PASSWORD reload The user can access the assigned database: $ mysql -u USERNAME -pUSER_PASSWORD USER_DATABASE Remove an user: mysql> drop user USERNAME@HOSTNAME; Or mysql> delete from mysql.user where User='USERNAME' and Host='HOSTNAME'; mysql> revoke all privileges on *.* from USERNAME@HOSTNAME; mysql> revoke grant option on *.* from USERNAME@HOSTNAME; mysql> flush privileges; Show all MySQL users: mysql> select user, host from mysql.user; # show only user name and related host name for every user mysql> select * from mysql.user; # show detailed information for every user Show all databases: mysql> show databases; Show all tables in the current database: mysql> show tables; mysql> show table status; # provide information about every table Show all fields (coloumns) of a table: mysql> show fields from TABLE; # same as describe TABLE; mysql> show fields from TABLE from DB; # show fields of a table from another database mysql> show full fields from TABLE; # also lists privileges available to the current user Show all indexes (keys) of a table: mysql> show index from TABLE; mysql> show index from TABLE from DB; # show indexes of a table from another database Create an index (key) for a field (coloumn): mysql> alter table TABLE add index (`FIELD`) ; Count all records within a table: mysql> select count(*) from TABLE; Backup a database to a MySQL dump file (structure only): mysqldump -no-data -u MYSQLUSER -pPASSWORD DATABASE > MYSQLDUMP.sql Backup a database to a MySQL dump file (data only): mysqldump -c --no-create-db --no-create-info -u MYSQLUSER -pPASSWORD DATABASE > MYSQLDUMP.sql Backup a database to a MySQL dump file (structure and data): mysqldump -c --add-drop-database --add-drop-table --add-locks -u MYSQLUSER -pPASSWORD DATABASE > MYSQLDUMP.sql Back up a MySQL database into a GZIP file: mysqldump -c --add-drop-database --add-drop-table --add-locks -u MYSQLUSER -pPASSWORD DATABASE | gzip -9v > MYSQLDUMP_`date +%Y%m%d`.sql.gz Restore a database from a MySQL dump file: mysql -h localhost -u MYSQLUSER -pPASSWORD DATABASE < MYSQLDUMP.sql Delete a database: mysql> drop database if exists DATABASE; Delete a table: mysql> drop table if exists TABLE; Delete a field: mysql> alter table TABLE drop FIELD; Delete an index: mysql> drop index INDEX on TABLE; Empty a table without deleting it: mysql> truncate table TABLE; Change engine type: mysql> alter table TABLE type = MYISAM; # change the engine tipe of TABLE to MyISAM Analyzes indexes of a table: # for MyISAM and BDB tables only mysql> analyze table TABLE; Check a table for errors: mysql> check table TABLE; Attempt to repair a corrupted table mysql> repair table TABLE; Optimize a table (defragment and rebuild indexes): mysql> optimize table TABLE; Show MySQL server status: mysql> show status; Check running MySQL processes (queries): $ mysqladmin -h localhost -u root -pROOT_PASSWORD processlist Or, from the MySQL console: mysql> show processlist; Kill a MySQL process: $ mysqladmin -u root -pROOT_PASSWORD kill ID Or, from the MySQL console: mysql> kill ID; Quit MySQL console: mysql> quit Show MySQL version: mysql -V To restart MySQL: /etc/init.d/mysql restart # If MySQL fails to start make sure the directories /var/log/mysql and /var/log/mysqld are owned by mysql:adm Run a MySQL file and store output into another file: mysql -u USER --password=PASSWORD DATABASE_NAME < SOURCE.sql > DESTINATION.txt This may fix these errors that may happen after an upgrade: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' ERROR 1577 (HY000) at line 1: Cannot proceed because system tables used by Event Scheduler were found damaged at server start apt-get install php5-mysql mysql-server mysql-server-5.1 mv /etc/mysql/my.cnf /etc/mysql/my.cnf.bak1 mv /etc/mysql/my.cnf.dpkg-dist /etc/mysql/my.cnf /etc/init.d/mysql start apt-get install php5-mysql mysql-server mysql-server-5.1


# If you can't see the phpmyadmin directory into /var/www/ then the package likely installed it into /usr/share/ , in this case you have to link it manually to access it from the web ln -s /usr/share/phpmyadmin /var/www/ Install phpMyAdmin manually: # You may want to install phpMyAdmin manually, especially if your Debian is set to Stable and there's no 'phpmyadmin' package available. # Create a directory for phpMyAdmin mkdir /usr/share/phpmyadmin # Create a directory to save phpMyAdmin source mkdir /usr/share/phpmyadmin/src # Go to phpmyadmin source directory and use it as a work directory cd /usr/share/phpmyadmin/src # Download latest version of phpMyAdmin wget -P /usr/share/phpmyadmin/src # Download phpMyAdmin public keyring to verify the source wget -P /usr/share/phpmyadmin/src # Import phpMyAdmin public keyring into GPG gpg --import phpmyadmin.keyring # Get phpMyAdmin public key wget -P /usr/share/phpmyadmin/src # Verify phpMyAdmin source gpg --verify phpMyAdmin-latest-all-languages.tar.gz.asc # You should get something like: ---------- gpg: assuming signed data in 'phpMyAdmin-latest-all-languages.tar.gz' gpg: Signature made Thu 15 Oct 2020 20:10:40 CEST gpg: using RSA key 3D06A59ECE730EB71B511C17CE752F178259BD92 gpg: Good signature from "Isaac Bennetch <>" [unknown] gpg: aka "Isaac Bennetch <>" [unknown] gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: 3D06 A59E CE73 0EB7 1B51 1C17 CE75 2F17 8259 BD92 ---------- # Verify that the key returned by GPG is the same as shown in phpMyAdmin's website for the given release manager person: # In this case, Isaac Bennetch's fingerprint is 3D06 A59E CE73 0EB7 1B51 1C17 CE75 2F17 8259 BD92 # If everything is OK, unpack the compressed file into phpMyAdmin's directory tar xvf phpMyAdmin-latest-all-languages.tar.gz --strip-components=1 -C /usr/share/phpmyadmin/ # You can now remove the download directory (note that if left in the position given in this tutorial, it will also be available from the Web) cd /usr/share/phpmyadmin/ rm /usr/share/phpmyadmin/src/* rmdir /usr/share/phpmyadmin/src # Create a configuration file for phpMyAdmin cp /usr/share/phpmyadmin/ /usr/share/phpmyadmin/ # Edit phpMyAdmin configuration file jed /usr/share/phpmyadmin/ # And set a password for the cookies $cfg['blowfish_secret'] = 'PUT_YOUR_PASSWORD_HERE'; # Set modes for the configuration file chmod 660 /usr/share/phpmyadmin/ # Set user and group for phpMyAdmin's directory chown -R www-data:www-data /usr/share/phpmyadmin # Create a symlink to make it accessible from the Webserver ln -s /usr/share/phpmyadmin /var/www/ # Make phpMyAdmin available from the Web, for example: jed /etc/apache2/sites-enabled/default.conf --------- <VirtualHost mysql.EXAMPLE.COM:80> ServerName mysql.EXAMPLE.COM ServerAdmin webmaster@EXAMPLE.COM DocumentRoot "/var/www/phpmyadmin" ServerSignature On LogLevel Warn ErrorLog /var/log/apache2/phpmyadmin_error.log CustomLog /var/log/apache2/phpmyadmin_access.log combined </VirtualHost> --------- # If you want to upgrade manually phpMyAdmin: # Make a backup of the current phpMyAdmin directory cp -rp /usr/share/phpmyadmin /usr/share/phpmyadmin_bak # Empty phpMyAdmin directory without removing it rm -r /usr/share/phpmyadmin/* # Follow the steps to install phpMyAdmin manually except for: Create a directory for phpMyAdmin (if you've emptied the existing one without removing it), Create a symlink to make it accessible from the Webserver, Make phpMyAdmin available from the Web. # If the new version works properly, you can remove the backup you've created rm -r /usr/share/phpmyadmin /usr/share/phpmyadmin_bak # Restart Apache Webserver /etc/init.d/apache2 restart


apt-get install sqlite sqlite3 libsqlite3-dev # To fix these errors: sqlite_exec(): attempt to write a readonly database; sqlite_exec(): unable to open database file chmod 666 *.sdb chmod 777 the directory containing the .sdb file


If you want to have https websites (so that the client can access the server securely through an encrypted connection to the server) hosted in your webserver, there are two ways: with certbot and the free service offered by EFF Let's Encrypt, or with a commercial certification authority. This is the procedure for EFF Let's Encrypt: jed /etc/apache2/ports.conf Add these lines: <IfModule ssl_module> Listen 443 </IfModule> apt install certbot python3-certbot-apache Make sure there are no redirects in /etc/apache2/sites-enabled/default.conf that may prevent Certbot to generate proper redirects from HTTP to HTTPS certbot --apache -d EXAMPLE.COM -d WWW.EXAMPLE.COM This is the output of certbot: Created an SSL vhost at /etc/apache2/sites-enabled/default-le-ssl.conf Deploying Certificate to VirtualHost /etc/apache2/sites-enabled/default-le-ssl.conf Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2 Redirecting vhost in /etc/apache2/sites-enabled/default.conf to ssl vhost in /etc/apache2/sites-enabled/default-le-ssl.conf You should test your configuration at: certbot renew --dry-run # Test renewal IMPORTANT NOTES: - Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal. This is the procedure for a commercial certification authority: Certificates and keys should be stored in these directories: /etc/ssl/certs # for certificates /etc/ssl/private # for keys Generate a Key: openssl genrsa -out /etc/ssl/private/DOMAIN.key 2048 Enter a valid domain name Generate a request certificate: openssl req -new -sha256 -key /etc/ssl/private/DOMAIN.key -out The only fields you must fill are Organization Name (eg, company) and Common Name (e.g. server FQDN or YOUR name), you can leave empty all other fields. Note that fields with a given default value must be filled with a dot (.) to make them empty, if you simply press RETURN the default value will be used instead: ---------- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:. State or Province Name (full name) [Some-State]:. Locality Name (eg, city) []: Organization Name (eg, company) [Internet Widgits Pty Ltd]:COMPANY Organizational Unit Name (eg, section) []: Common Name (e.g. server FQDN or YOUR name) []:DOMAIN Email Address []: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []: ---------- If you want to validate your domain (to claim its possession) via e-mail, enable the e-mail address admin@DOMAIN (that is, make sure you can receive e-mails to admin) for validation Buy a certificate from a Certificate Authority (CA) Validate the domain (claim it as yours) according to the procedure requested by the Certificate Authority Download the certificates ( ca-bundle-client.crt , DOMAIN.crt ) Upload the certificates into /etc/ssl/certs (the private key you've generated should already be into /etc/ssl/private/ ) Edit the Apache configuration file: jed /etc/apache2/sites-enabled/default.conf Create a VirtualHost for the DOMAIN for port 443 with the following directives: <VirtualHost DOMAIN:443> SSLEngine on SSLCertificateFile /etc/ssl/certs/DOMAIN.crt SSLCertificateKeyFile /etc/ssl/private/DOMAIN.key SSLCertificateChainFile /etc/ssl/certs/ca-bundle-client.crt # HSTS (mod_headers is required) (15768000 seconds = 6 months) # Header always set Strict-Transport-Security "max-age=15768000" # ... </VirtualHost> For example: <VirtualHost> SSLEngine on SSLCertificateFile /etc/ssl/certs/example_com.crt SSLCertificateKeyFile /etc/ssl/private/example_com.key SSLCertificateChainFile /etc/ssl/certs/ca-bundle-client.crt # HSTS (mod_headers is required) (15768000 seconds = 6 months) # Header always set Strict-Transport-Security "max-age=15768000" ServerName ServerAdmin DocumentRoot "/var/www/" ServerSignature On LogLevel Warn ErrorLog /var/log/apache2/example-com_error.log CustomLog /var/log/apache2/example-com_access.log combined </VirtualHost> If you still want the website to be available via http (without encryption), you also have to configure it without SSL (normally for port 80). Note that it can be configured to have a different document directory () and thus provide different content from the https (encrypted) website. <VirtualHost> ServerName ServerAdmin DocumentRoot "/var/www/" ServerSignature On LogLevel Warn ErrorLog /var/log/apache2/example-com_error.log CustomLog /var/log/apache2/example-com_access.log combined </VirtualHost> If you want to redirect all http traffic to https for a portion of the website, add this line inside the VirtualHost for http (port :80) Redirect /ALWAYS_HTTPS_DIRECTORY_NAME If you want to redirect all http traffic to https for the whole website, add this line inside the VirtualHost for http (port :80) Redirect / Restart the webserver when you're done with editing the configuration file: /etc/init.d/apache2 restart When you renew a certificate, you'll have to upload the newly reissued certificates ( ca-bundle-client.crt , DOMAIN.crt ) replacing the old ones into /etc/ssl/certs and restart the webserver.

Password protected directories in Apache

# Create a password file, it should be placed in a directory not served by the webserver (for example, /var/ , which normally is out of the htdocs directory) touch PATH/.htpasswd chmod 644 PATH/.htpasswd # Create users and assign passwords to them htpasswd -b PATH/.htpasswd USER PASSWORD # Create a password for every user. The same statement can be used to change a password of an already existing user htpasswd -D PATH/.htpasswd USER # Delete a user from the password file # Create an access control file in the directory containing the files with restricted access # Use Require valid-user to allow access to any user in the password file, or list specific users allowed to access the restricted files jed PATH_TO_PROTECT/.htaccess --- AuthUserFile PATH/.htpasswd AuthName "Enter Password" AuthType Basic <Limit GET POST> # Require valid-user Require user USER1 Require user USER2 </Limit> ---

Web site statistics

Fetch stats from webserver's logs: grep " 404 " /var/log/apache2/ACCESS.log | awk -F\" '$9=404{print $9" "$2}' | sort | uniq -c | sort -rg | head --lines=25 # Show top 404 error ("Not Found") requested pages grep "GET /" /var/log/apache2/ACCESS.log | awk {'print $7'} | sort | uniq -c | sort -g | tail --lines=15 | tac # Show top accessed pages awk {'print $7'} /var/log/apache2/ACCESS.log | grep ".php" | sort | uniq -c | sort -g | tail --lines=15 | tac # Show top accessed PHP pages grep -i "GET /PATH/DOCUMENT" /var/log/apache2/ACCESS.log | awk '{print $1}' | sort -n | uniq -c | sort -rn | head --lines=25 # Show top IPs accessing the given DOCUMENT (web page)


apt-get install webalizer jed /etc/webalizer.conf # or jed /etc/webalizer/webalizer.conf # or another custom .conf file webalizer /var/log/apache2/access.log.1 # create a webalizer report for access.log.1 webalizer /var/log/apache2/example-com_access.log # create a webalizer report for example-com_access.log If you get the following error message: Error Opening file /usr/share/GeoIP/GeoIP.dat you can fix it installing the GeoIP database: apt-get install geoip-database To have statistics available on the web for many websites, create a different access log, webalizer configuration file and output directory, for every website and a configuration file, and call webalizer from a script. Example: # 1. Set Apache log files jed /etc/apache2/sites-enabled/default.conf <VirtualHost> [...] CustomLog /var/log/apache2/example-com_www_access.log combined [...] </VirtualHost> <VirtualHost> [...] CustomLog /var/log/apache2/example-net_my_access.log combined [...] </VirtualHost> /etc/init.d/apache2 restart # 2. Create output directories mkdir /var/www/webalizer mkdir /var/www/webalizer/ mkdir /var/www/webalizer/ # 3. Assign ownership of the directories to www-data chown www-data:www-data /var/www/webalizer/ chown www-data:www-data /var/www/webalizer/ # 4. Create custom Webalizer configuration files jed /etc/webalizer/ LogFile /var/log/apache2/example-com_www_access.log OutputDir /var/www/webalizer/ Incremental yes HostName HideSite * HideReferrer [...] jed /etc/webalizer/ LogFile /var/log/apache2/example-net_my_access.log OutputDir /var/www/webalizer/ Incremental yes HostName HideSite * HideReferrer [...] # 5. Create a script that invokes webalizer for every website mkdir /etc/scripts jed /etc/scripts/ --- #!/bin/bash # Webalize webalizer -c /etc/webalizer/>/dev/null webalizer -c /etc/webalizer/>/dev/null --- Sample lines to add to Crontab: --- 1 0,12 * * * /var/www/scripts/>/dev/null 21 6 * * * /var/www/scripts/>/dev/null --- The first line tells Crontab to invoke Webalizer every day at 00:01 and 12:01, the second line makes Crontab invoke Webalizer every day at 6:21 . This is because logs start and end at a certain hour of the day (for example, 06:26), and you'd miss all the hours between last call of Webalizer, every day. To know the exact time when your logs starts and stops check the head and tail of the previous log, for example: head --lines=10 /var/log/apache2/www.example.net_access.log.1 , tail --lines=10 /var/log/apache2/www.example.net_access.log.1 # If you want to reset information cached from previous runs of Webalizer (especially if you've set Incremental yes in the webalizer configuration file), delete the files webalizer.current and webalizer.hist in the Webalizer OutputDir. # Example: # rm /var/www/webalizer/webalizer.current # rm /var/www/webalizer/webalizer.hist

Please DONATE to support the development of Free and Open Source Software (PayPal, Credit Card, Bitcoin, Ether)

Page issued on 25-Sep-2022 04:37 GMT
Copyright (c) 2022 Geody - Legal notices: copyright, privacy policy, disclaimer