Tag: Apache

Error “No such file or directory: AH02454: FCGI: attempt to connect to Unix domain socket /run/php/php8.1-fpm.sock (*:80) failed” (SOLVED)

Debian and derivative distributions (Ubuntu, Linux Mint, Kali Linux, and many others) may experience a “FCGI: attempt to connect to Unix domain socket /run/php/php8.1-fpm.sock (*:80) failed” error when migrating from PHP 8.1 to PHP 8.2.

Apache web server log

sudo tail /var/log/apache2/error.log

contains the following error messages:

[Sun Jan 29 03:05:45.213609 2023] [proxy:error] [pid 1313500] (2)No such file or directory: AH02454: FCGI: attempt to connect to Unix domain socket /run/php/php8.1-fpm.sock (*:80) failed
[Sun Jan 29 03:05:45.213763 2023] [proxy_fcgi:error] [pid 1313500] [client 127.0.0.1:58950] AH01079: failed to make connection to backend: httpd-UDS
[Sun Jan 29 03:06:39.789031 2023] [proxy:error] [pid 1313496] (2)No such file or directory: AH02454: FCGI: attempt to connect to Unix domain socket /run/php/php8.1-fpm.sock (*:80) failed
[Sun Jan 29 03:06:39.789110 2023] [proxy_fcgi:error] [pid 1313496] [client 127.0.0.1:50024] AH01079: failed to make connection to backend: httpd-UDS
[Sun Jan 29 03:06:41.336218 2023] [proxy:error] [pid 1313499] (2)No such file or directory: AH02454: FCGI: attempt to connect to Unix domain socket /run/php/php8.1-fpm.sock (*:80) failed
[Sun Jan 29 03:06:41.336297 2023] [proxy_fcgi:error] [pid 1313499] [client 127.0.0.1:50040] AH01079: failed to make connection to backend: httpd-UDS
[Sun Jan 29 03:07:24.027400 2023] [proxy:error] [pid 1313497] (2)No such file or directory: AH02454: FCGI: attempt to connect to Unix domain socket /run/php/php8.1-fpm.sock (*:80) failed
[Sun Jan 29 03:07:24.027445 2023] [proxy_fcgi:error] [pid 1313497] [client 127.0.0.1:44688] AH01079: failed to make connection to backend: httpd-UDS
[Sun Jan 29 03:09:55.008467 2023] [proxy:error] [pid 1504919] (2)No such file or directory: AH02454: FCGI: attempt to connect to Unix domain socket /run/php/php8.1-fpm.sock (*:80) failed
[Sun Jan 29 03:09:55.008530 2023] [proxy_fcgi:error] [pid 1504919] [client 127.0.0.1:38382] AH01079: failed to make connection to backend: httpd-UDS

Sites and engines that use PHP, such as phpMyAdmin, give the following error:

503 Service Unavailable
Service Unavailable

The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.
Apache/2.4.55 (Debian) Server at localhost Port 80

The essence of the problem is indicated in the web server logs – it is impossible to connect to the php8.1-fpm.sock socket. This is a fairly predictable problem when changing the PHP version, in this case from PHP 8.1 to PHP 8.2.

FPM (FastCGI Process Manager, FastCGI process manager) is an alternative implementation of PHP FastCGI with several additional features commonly used for high load sites.

To disable an outdated version of FPM, run the following commands:

sudo a2disconf php8.1-fpm
sudo systemctl restart apache2

At this point, engines and sites that don't use FPM should already be working fine.

If you are really using FPM and want to enable the new version, then run the following commands:

sudo a2enconf php8.2-fpm
sudo systemctl reload apache2
sudo systemctl restart apache2.service
sudo systemctl restart php8.2-fpm

phpMyAdmin error “Error: Undefined constant “SODIUM_CRYPTO_SECRETBOX_KEYBYTES”” (SOLVED)

On Arch Linux, when trying to use the phpMyAdmin 5.3 pre-release, I encountered an error:

Error: Undefined constant "SODIUM_CRYPTO_SECRETBOX_KEYBYTES"

Checking in Debian showed that there is no such problem with phpMyAdmin 5.3.

The reason for the error is that sodium support is not enabled.

How to enable sodium on Arch Linux (Manjaro, BlackArch)

To enable sodium support in Arch Linux and derivative distributions (Manjaro, BlackArch) follow these steps.

Install the php-sodium package:

sudo pacman -S php-sodium

Open the /etc/php/php.ini file:

sudo gedit /etc/php/php.ini

Find the line in it

;extension=sodium

and uncomment it to get:

extension=sodium

Restart the web server for the changes to take effect:

sudo systemctl restart httpd.service

This will enable sodium support and the error in phpMyAdmin 5.3 will disappear.

How to show all errors in PHP 8

How to display all errors in PHP 8

By default, PHP 8 disables showing errors, so if there is a problem while executing a PHP script, nothing will be displayed on the screen. If an error in the program occurred before the output of the HTML code, then you will see a white screen of the web browser.

Where is the error output configured in PHP

Error output is configured in:

  • script code
  • .htaccess file
  • in the PHP configuration file (for example, in php.ini)

The settings in the script code only affect the behavior of the program in which the settings are made.

The settings in the .htaccess file affect all scripts in that directory and subdirectories.

The settings in the php.ini configuration file affect all PHP scripts that are run unless their error output settings are overridden.

Remember that error reporting is very useful while writing and debugging code, but on production servers, error reporting should be turned off to prevent sensitive data from being leaked and making it harder for an attacker to hack the site.

Configuring error output in PHP script

To display all errors, add the following lines to the beginning of the script:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

These settings enable the output of all errors and warnings to the user's web browser.

Warnings about the use of deprecated constructs will be displayed.

Error output to the web server logs is configured separately.

Remember that if fatal errors occur, that is, when the script could not even run due to incorrect PHP syntax, then the rules specified in the php.ini or .htaccess file will be used to output errors. This is due to the fact that if the syntax is incorrect, the PHP interpreter does not understand the entire file, including the above directives. That is, if a semicolon or a curly brace is missing in the code, then errors will be displayed in accordance with the settings in the php.ini file.

Configuring PHP error output in .htaccess file

Enabling error output in the .htaccess file is done by the following directives:

php_flag display_startup_errors on
php_flag display_errors on

For them to work, the web server must have .htaccess files enabled.

Error output to the web server log is performed by the following directive:

php_value error_log logs/all_errors.log

Setting the output of all errors in the php.ini file

The php.ini file is the PHP configuration file.

PHP can use more than one configuration file during its operation.

Location of php.ini file:

  • In Debian and derivative distributions (Ubuntu, Linux Mint, Kali Linux and others), it depends on the PHP version, for example, for PHP 8.1 the path to the file is: /etc/php/8.1/apache2/php.ini
  • On Arch Linux and derivative distributions (Manjaro, BlackArch and others): /etc/php/php.ini

In the php.ini file you will find the following directives:

display_errors = Off
display_startup_errors = Off

To enable error reporting, replace them with:

display_errors = On
display_startup_errors = On

The default value of error_reporting is set to:

error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

This means that all errors are printed except for deprecation warnings and warnings caused by strict code checking.

To display all errors and warnings, set the following value:

error_reporting = E_ALL

Common Values:

  • E_ALL (Show all errors, warnings and notices including coding standards.)
  • E_ALL & ~E_NOTICE (Show all errors, except for notices)
  • E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
  • E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)

See the link for details: https://www.php.net/manual/errorfunc.constants.php

In order for the changes made in the php.ini file to take effect, a restart of the web server is required.

  • In Debian and derivative distributions (Ubuntu, Linux Mint, Kali Linux and others), this is done with the command:
sudo systemctl restart apache2.service
  • In Arch Linux and derivative distributions (Manjaro, BlackArch and others), this is done with the command:
sudo systemctl restart httpd.service

To check that the php.ini file settings are actually applied, create a file, for example, named info.php and copy into it:

<?php
phpinfo();

If you created the file in the root folder of the web server, in a web browser open http://localhost/info.php.

The following screenshot shows that error output is disabled in the php.ini file:

This screenshot shows that error output is enabled in the php.ini file:

Outputting errors to the web server log

Error output to the web server log is configured in the php.ini file.

The following directive is used for this:

log_errors = On

The location of the error file is configured in the web server configuration.

The “error_reporting('all');» и ошибка «Uncaught TypeError: error_reporting()”

When trying to use the following construct:

error_reporting('all');

You will encounter the Uncaught TypeError: error_reporting() error.

Full error log:

[Wed Jul 06 07:29:19.410966 2022] [php:error] [pid 14101] [client 127.0.0.1:58402] PHP Fatal error: Uncaught TypeError: error_reporting(): Argument #1 ($error_level) must be of type ?int, string given in /srv/http/suip/index.php:3\nStack trace:\n#0 /srv/http/suip/index.php(3): error_reporting('all')\n#1 {main}\n thrown in /srv/http/suip/index.php on line 3, referer: http://localhost/suip/

Instead of 'all' you need to provide a constant expressing the level of the error message. Valid values are provided on this page: https://www.php.net/manual/errorfunc.constants.php

The following entry is correct for PHP 8 and means to show all errors, notes, and recommendations:

error_reporting(E_ALL);

Apache window appears and immediately disappears (SOLVED)

When I click on httpd.exe, a black window flickers and then disappears

Apache (httpd) is a command line utility. Strictly speaking, this is a service that is designed to run in the background without a graphical interface. That is, Apache does not have a graphical interface in the form of a familiar window. Therefore, Windows users may feel that the program starts in an unusual way.

To run the program, you need to open a Windows Terminal window (or PowerShell). To do this, press the key combination Win+x, and select Windows Terminal (Admin):

Then you can proceed in two ways.

The first option: you can simply drag and drop the executable file into the command line window. The executable is httpd.exe.

The second option: on the command line, you can change the current working directory to the one where the Apache executable files are located. For example, my program is located in the C:\Apache24\bin\ folder, to change the current working folder, the cd command is used, after which the folder to which you want to go is indicated, in my case the command looks like this:

cd C:\Apache24\bin\

As you can see from the screenshot, the C:\Users\MiAl folder has been changed to C:\Apache24\bin\.

Now, to run the program, it is enough to type the name of the executable file indicating the current folder. The current folder is indicated by a dot (.), then you need to put a backslash, it turns out like this:

.\httpd.exe

Apache is a network service, that is, a program that uses a computer network for its work. Specifically, Apache listens for incoming connections on port 80 (opens a port). For this reason, the Windows Firewall asks whether to allow access to the Apache HTTP Server program, select “Allow access”.

Already at this stage, the web server is running and you can open the address http://localhost/ in a web browser

To stop the service, press Ctrl+c.

Typically, command-line utilities support various options that can be specified with a space after the executable file name.

Also, utilities usually have built-in help on available options, which can be displayed using the -h option or the --help option.

For example:

.\httpd.exe -h

In addition to command line options, many services are configured using configuration files, which are text files with a specific syntax. For Apache in Windows this is the C:\Apache24\conf\httpd.conf file.

To get a complete web server with all the necessary components, follow the steps from the guide “How to install Apache web server with PHP, MySQL and phpMyAdmin on Windows”.

Configuring Apache Web Server to Run Perl Programs on Windows

Perl scripts can be run in the Apache environment in the same way as PHP scripts. To do this, you need to make a small setting.

I installed the web server according to this instruction, if you installed according to a different instruction, then edit the paths to suit your values.

1. Installing Perl on Windows

Download Perl for Windows from https://www.activestate.com/products/activeperl/downloads/

Run the downloaded .exe file – installation can be done with default options.

2. Configuring Apache to run Perl CGI

Now open the httpd.conf file for editing, I have it located along the path C:\Server\bin\Apache24\conf\httpd.conf.

Find the line there

Options Indexes FollowSymLinks

and add ExecCGI to it. You should get the following line (ATTENTION: you may have a different set of options):

Options Indexes FollowSymLinks ExecCGI

Now find the line:

#AddHandler cgi-script .cgi

Uncomment it, that is, remove the # at the beginning of the line and add .pl to the end of the line. The new line will look something like this:

AddHandler cgi-script .cgi .pl

3. Restart Apache

c:\Server\bin\Apache24\bin\httpd.exe -k restart

4. Run the Perl CGI test page

In the folder for your sites (mine is C:\Server\data\htdocs\) create a file test.pl and copy into it:

#!C:\Perl64\bin\perl.exe
print "Content-type: text/html; charset=iso-8859-1\n\n";
print "<phtml>";
print "<body>";
print "Test Page";
print "</body>";
print "</html>";

Pay attention to the line #!C:\Perl64\bin\perl.exe – if you have a different path to the perl.exe file, then edit the line accordingly.

Open this page in a web browser: http://localhost/test.pl

The inscription should appear

Test Page

As shown in the screenshot below:

How to fix “Configuration File (php.ini) Path” no value (SOLVED)

The phpinfo function shows complete information about the PHP environment, including which modules are enabled, where the configuration files are located, with which options the PHP binaries were compiled, and much more.

To use this function in the web server folder create a file and copy to it:

<?php

phpinfo ();

Save the file and open it in a web browser.

Why Configuration File (php.ini) Path has no value

As the name of the item “Configuration File (php.ini) Path” implies, this is the path to the configuration file php.ini. The php.ini file is important because it enables and disables modules, sets limits on the use of system hardware resources, and makes all other PHP settings.

As you can see in the screenshot, “Configuration File (php.ini) Path” is defined as “no value", that is, it is not set. You might think that something was done wrong and PHP works without modules.

But in fact, PHP and the web server on the computer from which the screenshot was taken are working as expected. Pay attention to the next item “Loaded Configuration File” after the highlighted line, it contains the value C:\Server\bin\PHP\php.ini, that is, the configuration file is loaded.

As for the “Configuration File (php.ini) Path”, the path to the file where php.ini is searched for by default is written here – this value is specified when compiling PHP, you do not need to worry about it.

That is, you need to pay attention only to the “Loaded Configuration File”, because if there is also “no value”, then it really means that the php.ini configuration file is not loaded and not used.

If some modules do not work, then carefully check the contents of php.ini – have you really uncommented the required lines?

After making changes to the php.ini file, remember to restart the web server for the changes to take effect.

How to install a web server (Apache, PHP, MySQL, phpMyAdmin) on Linux Mint, Ubuntu and Debian

If you are a webmaster, or a PHP programmer, or you just need to run a website on your computer, then you can do it using a web server. On Linux, the web server (Apache) and related components (PHP, MySQL, phpMyAdmin) are installed in just a few commands.

This tutorial will show you how to set up a web server for sites on Linux Mint, Ubuntu and Debian.

How to install Apache, PHP, MySQL, phpMyAdmin on Linux Mint, Ubuntu and Debian

We will do most of the operations in the command line - the Linux terminal.

Open a terminal and run the following two commands in it:

sudo apt update
sudo apt install apache2 default-mysql-server php phpmyadmin

Answer No to the configuration prompt with dbconfig-common:

Use the Tab key to move between items and Enter to continue.

Select “apache2”:

Use the Space key to select items, use the Tab key to move between items, and press Enter to continue.

That's all! The web server (a bunch of Apache, PHP, MySQL, phpMyAdmin) is installed and ready to work. Open the link http://localhost/ in your browser

You will see the standard Apache page:

phpMyAdmin is available at http://localhost/phpmyadmin/

To start the web server every time you turn on the computer, run the command:

sudo systemctl enable apache2
sudo systemctl enable mysql

How to change URL path of phpMyAdmin. How to enable and disable phpMyAdmin

If during the installation of phpMyAdmin you chose not to configure it for use with the Apache web server, use the command to enable phpMyAdmin:

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-enabled/

Restart the web server for the changes to take effect:

sudo systemctl restart apache2

To disable phpMyAdmin use the command:

sudo rm /etc/apache2/conf-enabled/phpmyadmin.conf

Restart the web server for the changes to take effect:

sudo systemctl restart apache2

There is an important line in the /etc/phpmyadmin/apache.conf file:

Alias /phpmyadmin /usr/share/phpmyadmin

Its essence is that the URL /phpmyadmin (for example, http://localhost/phpmyadmin) begins to correspond to the /usr/share/phpmyadmin folder. That is, the phpMyAdmin files (scripts) are physically located in /usr/share/phpmyadmin, and not in the web server directory (for example, /var/www/html/).

Many automatic scanners of “hidden” files and folders of a web server and sites check the “phpmyadmin”, “pma” and other similar directories. You can hide your phpMyAdmin nicely by changing the Alias. For instance:

Alias /lkjgler94345 /usr/share/phpmyadmin

phpMyAdmin will now be available at http://localhost/lkjgler94345 - not easy to find.

phpMyAdmin setup

By default phpMyAdmin does not allow login without password. If you have not set a password for the MySQL DBMS, then you have two options to choose from:

  • set password
  • make changes to phpMyAdmin setting to allow passwordless login

It is recommended to set a password for the database. To change the password, you can use the script:

sudo mysql_secure_installation

If you want to allow logging into phpMyAdmin without a password, then open the file

sudo gedit /etc/phpmyadmin/config.inc.php

Find the second (there are two) line

// $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

and uncomment it (remove the two slashes from the beginning of the line) to get:

$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

Most likely, when connecting, you will receive a surprise in the form of the error “#1698 - Access denied for user 'root'@'localhost'”. Step-by-step actions for its solution in this manual.

Where are the sites on the Apache web server?

By default, the root folder for web documents is /var/www/html. In /var/www you can create your own virtual hosts.

The /var/www/html folder and all files inside it belong to the root user.

For you to be able to modify, add, delete files in this folder, you need to use sudo. For example, with the following command, you will open a file manager to manage the contents of a folder.

sudo nemo /var/www/html

All other programs that make changes to /var/www/html must also be run with sudo.

On a local server, for ease of use, you can make yourself the owner of this folder:

sudo chown -R $USER:$USER /var/www/html

Now you and the programs launched on your behalf do not need superuser privileges to work with the contents of this directory:

nemo /var/www/html

Apache index files

If the user requests from the web server not a file, but a directory, then the server looks for files index.html, index.php, index.htm, etc. in it. If these files are in this directory, then their contents are shown. These files are called index files. If there are two or more such files in a directory at once, then one of them is shown in accordance with the set priority.

You can see which files are index files for your server and in what order their priority is arranged in the file

sudo gedit /etc/apache2/mods-enabled/dir.conf

There you will see something like:

<IfModule mod_dir.c>
    DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule>

Typically, users want to move the PHP index file (index.php) to the first position after DirectoryIndex, so that something looks like this:

<IfModule mod_dir.c>
    DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

After making changes, save and close the file, restart the web server.

Conclusion

This tutorial showed you how to install Apache web server on your Linux Mint machine. In terms of its functionality, this server does not differ from the capabilities of hosting. You can test your sites on it, use it when learning PHP, install WordPress, etc. Moreover, this server can be made available to the local or even global network.

What is open_basedir for and how to use open_basedir

The open_basedir directive is specified in the PHP configuration file (php.ini) and sets the directories that PHP can access. Access refers to any actions with files: opening (for example, fopen() or gzopen()), writing and executing. If the open_basedir directive is set and an attempt is made to run a file that is outside the listed directories, the script will not run and will generate an error:

[Wed Apr 1 13:11:34 2020] PHP Warning: Unknown: open_basedir restriction in effect. File(/usr/share/seeker/template/nearyou/php/info.php) is not within the allowed path(s): (/srv/http/:/etc/webapps/:/usr/share/webapps/:/tmp/:/home/mial/) in Unknown on line 0

An example of the value of open_basedir:

open_basedir = /srv/http/:/etc/webapps/:/usr/share/webapps/:/tmp/:/home/mial/

In this example, PHP scripts are allowed to run, as well as operations with files in directories:

  • /srv/http/
  • /etc/webapps/
  • /usr/share/webapps/
  • /tmp/
  • /home/mial/

The open_basedir directive affects many functions. It makes most sense when used at the level of web server configuration files at the level of directories or virtual hosts.

By default, if the open_basedir value is not set, file operations are allowed in any directories on the computer (for which there are sufficient file permissions).

The open_basedir option can be extended to more than just functions for working with the filesystem; for example, if MySQL is configured to use the mysqlnd driver, then LOAD DATA INFILE is controlled by the open_basedir option. Many PHP functions also use open_basedir.

Special meaning . (dot) indicates that the script's working directory will be used as the base directory. However, this is a little dangerous, as the current directory of the script can be easily changed with chdir().

In httpd.conf, open_basedir can be turned off (for example, for some virtual hosts) in the same way as any other configuration directive:

php_admin_value open_basedir none

On Windows, separate directories with ; (semicolon). On all other systems, separate directories with : (colon). When running as an Apache module, open_basedir paths are automatically inherited from parent directories.

How to install Apache web server with PHP, MySQL and phpMyAdmin on Windows

Table of contents

1. Windows web server

2. How to install Apache on Windows

3. How to install PHP on Windows

4. PHP 8 setup

5. How to install MySQL on Windows

6. How to install phpMyAdmin on Windows

Conclusion


Windows web server

A web server is a program that is designed to process requests for websites and send website pages to users. The most popular example of a web server is Apache.

PHP is a programming language. Also, it called an environment for executing scripts written in PHP. In operating systems, including Windows, PHP can be installed independently, without a web server. In this case, programs (scripts) in PHP can be run from the command line. But web applications use PHP very often, this interpreter has become, in fact, the standard for web servers and therefore they are almost always installed together.

MySQL is a database management system (DBMS). It is also a standalone program, it is used to store data, search databases, modify and delete data. Web applications need persistent storage, so a DBMS is additionally installed for the web server. By the way, it is quite possible that you have heard about MariaDB - this is also a DBMS. MySQL came first, and then MariaDB forked from it. For web applications, both of these DBMS are interchangeable, that is, there is no difference. In this tutorial I will show the installation using MySQL as an example.

As for phpMyAdmin, this is just a PHP script that is designed to work with databases - it visually displays their contents, allows you to perform tasks in the graphical interface such as creating databases, creating tables, adding, changing and deleting information, etc. For this reason phpMyAdmin is quite popular, although it is not a required part of the web server.

The peculiarity of Apache and other web server components is that they have their roots in Linux. And these programs apply the basic concepts of this operating system in their work. For example, programs are very flexible in customization - you can install in any folder, sites can also be placed in any folder, including on another drive, not on the one where the web server itself is installed. Even the log files can be moved to the third disk and so on. The web server has many built-in modules - you can enable or disable them in any combination, you can add external modules. You can create many sites on the same web server and customize each site. But this flexible setting is done through text files - this is the approach (without a graphical interface) that allows you to describe any configuration

Do not be afraid of this - I will tell you what files need to be edited and what exactly to write in them.

We will not do any complex settings - our goal is just to install the web server on Windows. However, it would be strange not to use that kind of power in tuning at all. We will split the server into two directories: the first will contain executable files, and the second will contain data (website and database files). In the future, when the need arises to make backups of information or update the web server, you will understand how convenient this approach is!

We will install the server in a separate directory. To do this, create the “Server” directory in the root of the C:\ drive. Create 2 subdirectories in this directory: “bin” (for executable files) and “data” (for sites and databases).

Go to the “data” directory and create subfolders “DB” (for databases) and “htdocs” (for web sites) there.

Go to the “C:\Server\data\DB\” directory and create an empty “data” folder there.

For the operation of all components of the web server, the file “Visual C++ Redistributable for Visual Studio 2015-2019" is required - this is the official file from Microsoft. To download it follow the link. After downloading, run this file and complete the installation.

The preparatory steps are completed, we proceed to the installation of the web server components.

How to install Apache on Windows

Go to apachelounge.com/download and download the .zip archive with the web server:

Unpack the “Apache24” folder from this archive to “C:\Server\bin\”.

Go to the “C:\Server\bin\Apache24\conf\” directory and open the httpd.conf file with any text editor.

In it, we need to replace a number of lines.

Change

Define SRVROOT "c:/Apache24"

on

Define SRVROOT "c:/Server/bin/Apache24"

change

#ServerName www.example.com:80

on

ServerName localhost

change

DocumentRoot "${SRVROOT}/htdocs"
<Directory "${SRVROOT}/htdocs">

on

DocumentRoot "c:/Server/data/htdocs"
<Directory "c:/Server/data/htdocs">

change

DirectoryIndex index.html

on

DirectoryIndex index.php index.html index.htm

change

# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   AllowOverride FileInfo AuthConfig Limit
#
AllowOverride None

on

# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   AllowOverride FileInfo AuthConfig Limit
#
AllowOverride All

and change

#LoadModule rewrite_module modules/mod_rewrite.so

on

LoadModule rewrite_module modules/mod_rewrite.so

We save and close the file. That's it, Apache configuration is complete!

Open a command prompt (you can do this by pressing the Win+x keys at the same time). 

Select Windows PowerShell (Admin) there and copy there:

c:\Server\bin\Apache24\bin\httpd.exe -k install

Press Enter.

If you get a request from the firewall regarding Apache, then click Allow access.

Now we enter into the command line:

c:\Server\bin\Apache24\bin\httpd.exe -k start

And press Enter.

Now in the browser, type http://localhost/ and see the following:

This means the web server is running. To see the files there, add them to the c:\Server\data\htdocs\ directory - this is the main folder for the server data, where all sites will be located.

How to install PHP on Windows

Download PHP 8 from windows.php.net/download. Choose Thread Safe version, pay attention to select 64-bit computer architecture.

In the c:\Server\bin\ folder, create a “PHP” directory and copy the contents of the just downloaded archive into it.

In the file c:\Server\bin\Apache24\conf\httpd.conf at the very end we add the lines:

PHPIniDir "C:/Server/bin/PHP"
AddHandler application/x-httpd-php .php
LoadModule php_module "C:/Server/bin/php/php8apache2_4.dll"

And restart Apache:

c:\Server\bin\Apache24\bin\httpd.exe -k restart

In the c:\Server\data\htdocs\ directory, create a file called i.php, copy it to this file:

<?php
phpinfo ();

In your browser, open the link http://localhost/i.php. If you see something similar, then PHP is working:

PHP 8 setup

PHP is configured in the php.ini file. There is no php.ini in the zip archives intended for manual installation and for updates (this is done on purpose so that you do not accidentally delete your settings file during the update). But there are two others called php.ini-development and php.ini-production. Any of them, during manual installation, can be renamed to php.ini and further configured. On the localhost we will use php.ini-development.

Open the php.ini file with any text editor, looking for the line

;extension_dir = "ext"

and replace it with

extension_dir = "C:\Server\bin\PHP\ext\"

Now find the line group:

;extension=bz2
;extension=curl
;extension=ffi
;extension=ftp
;extension=fileinfo
;extension=gd
;extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=ldap
;extension=mbstring
;extension=exif      ; Must be after mbstring as it depends on it
;extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
;extension=oci8_19  ; Use with Oracle Database 19 Instant Client
;extension=odbc
;extension=openssl
;extension=pdo_firebird
;extension=pdo_mysql
;extension=pdo_oci
;extension=pdo_odbc
;extension=pdo_pgsql
;extension=pdo_sqlite
;extension=pgsql
;extension=shmop

and replace it with:

extension=bz2
extension=curl
extension=ffi
extension=ftp
extension=fileinfo
extension=gd
extension=gettext
extension=gmp
extension=intl
extension=imap
extension=ldap
extension=mbstring
extension=exif      ; Must be after mbstring as it depends on it
extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
extension=odbc
extension=openssl
;extension=pdo_firebird
extension=pdo_mysql
;extension=pdo_oci
extension=pdo_odbc
extension=pdo_pgsql
extension=pdo_sqlite
extension=pgsql
extension=shmop

now uncomment this line group:

;extension=soap
;extension=sockets
;extension=sodium
;extension=sqlite3
;extension=tidy
;extension=xsl 

it should look like this:

extension=soap
extension=sockets
extension=sodium
extension=sqlite3
extension=tidy
extension=xsl

With these actions, we enabled the extensions. They may be needed in different situations for different scripts. Save the file and restart Apache.

c:\Server\bin\Apache24\bin\httpd.exe -k restart

It is highly recommended to add the path to PHP to your “PATH” environment variable on Windows.

Related: How to add PHP path to %PATH% environment variable on Windows

How to install MySQL on Windows

The free version of MySQL is called MySQL Community Server. It can be downloaded from https://dev.mysql.com/downloads/mysql/. There is an executable installer on the same page, but I recommend downloading the ZIP archive.

On the download page, we are offered to register or log into an existing account - but this is optional. Just click on the link “No thanks, just start my download”.

Unpack the files from the just downloaded archive into the c:\Server\bin\ directory. The unpacked folder will be named approximately mysql-8.0.23-winx64 (depending on the version), rename it to mysql-8.0.

We go into this folder and create the my.ini file there. Now open this file with any text editor and add the following lines there:

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
datadir="c:/Server/data/DB/data/"
default_authentication_plugin=mysql_native_password

Save and close it.

The configuration is complete, but you still need to perform the initialization and installation, for this we open the command line as administrator and sequentially enter there:

C:\Server\bin\mysql-8.0\bin\mysqld --initialize-insecure --user=root
C:\Server\bin\mysql-8.0\bin\mysqld --install
net start mysql

At the end of this process, the automatically generated files should appear in the C:\Server\data\DB\data\ directory.

The MySQL service will now start every time Windows starts.

How to install phpMyAdmin on Windows

The phpMyAdmin download site is phpmyadmin.net.

Direct link to the most recent version: phpMyAdmin-latest-all-languages.zip.

Copy the contents of the just downloaded archive to the c:\Server\data\htdocs\ directory. Rename this folder to “phpmyadmin”.

In the c:\Server\data\htdocs\phpmyadmin\ directory, create a config.inc.php file and copy there:

<?php

/* Servers configuration */
$i = 0;

/* Server: localhost [1] */
$i++;
$cfg['Servers'][$i]['verbose'] = '';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['nopassword'] = true;
$cfg['Servers'][$i]['AllowNoPassword'] = true;

/* End of servers configuration */

$cfg['blowfish_secret'] = 'kjLGJ8g;Hj3mlHy+Gd~FE3mN{gIATs^1lX+T=KVYv{ubK*U0V';
$cfg['DefaultLang'] = 'en';
$cfg['ServerDefault'] = 1;
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';

?>

In the browser, type http://localhost/phpmyadmin/

Enter root as the username. Leave the password field blank.

Conclusion

That's it - you now have your own personal local web server on your home computer.

If suddenly something didn't work out for you, then most likely you missed a step or did it incorrectly - try to do everything exactly according to the instructions. If the problem persists, then write about your error in the comments.

How to set up Varnish, rule examples

Table of contents

1. How to change Varnish options

2. How to change cache retention time in Varnish

3. How to prevent Varnish from creating new cache for different browsers

4. A 403 page got into the Varnish cache and now it is shown to all users

5. How to make Apache logs show real IP address instead of 127.0.0.1 when used with Varnish

6. How to delete cookies that prevent caching

7. How to exclude certain pages from caching

8. How to exclude the home page from caching

9. How to increase the size of the Varnish cache

10. How to increase connection timeout in Varnish

11. How to exclude a specific site from Varnish caching

12. How to cache only a specific domain in Varnish

13. How to redirect HTTP to HTTPS in Varnish

14. How to delete cookies from all hosts except pages of a specific host

15. How to remove cookies from all pages except specific URLs

16. Adding and Removing HTTP Headers

17. Additional documentation


Once you've installed and configured Varnish to work with your web server. It would seem that everything is working fine and now you can move on to other things. But the truth is, with the default settings, Varnish is (almost) completely useless. The point is that by default:

  • cache storage time 2 minutes
  • a NEW cache is created for EACH User Agent. That is, if a page was requested by a user with a Chrome browser of one version, and then a user came with a different version of Chrome or with a different browser, then a new page will be created for him, instead of showing the one saved in the cache.

That is, the cache stores data for 2 minutes, which with a probability of 99% will not be shown to anyone for these two minutes, and then the data is deleted.

Moreover, with the default settings, Varnish is even harmful: a page with a response code of 503 (error on the server) or 403 (access denied) may be cached and this page will show everyone even when the problem is fixed.

In general, even though many tutorials on the Internet end up after installing Varnish and setting up a web server, you need to continue and do everything right. This is what this article is about. Here we will cover the minimum required configuration of Varnish to be useful and not harmful, and will also list examples of Varnish configuration that you can use in various situations.

How to change Varnish options

You can configure Varnish in the /etc/varnish/default.vcl configuration file, as well as by editing the command line launch options:

systemctl edit --full varnish

We will use both methods.

For the changes made in the default.vcl file to take effect, you must run the command:

systemctl reload varnish

This command will reload the configuration but keep the cache.

To make the changes made to the start command take effect, you must run:

systemctl restart varnish

This command will not save the cache - it will be cleared.

How to change cache retention time in Varnish

By default, Varnish keeps the cache for only 2 minutes - it is not enough for many situations.

The issue of storing the cache in Varnish is quite complex and can be devoted to a separate article. Here's a look at the basics.

First, there are three periods that Varnish keeps data in its cache:

  • TTL - Time To Live. This is the lifetime of the data. This is the period in which the data is stored in the cache and is considered fresh. “Fresh” - this means that when a request is received to show the page, the contents of the cache will be returned.
  • Grace. Grace period. This period comes after TTL. The data is still stored in the cache, and when a request is received for it, data from the cache is returned, at the same time a data update is started - a request is made to the web server.
  • Keep. Storage period. This is the period after TTL and Grace. The data is still stored in the cache, but is served to the user under certain conditions.

All these periods can be customized:

  • in the config file
  • in the command line
  • via HTTP headers

We will use the configuration file /etc/varnish/default.vcl. Open it:

vim /etc/varnish/default.vcl

The settings need to be made in the vcl_backend_response section. There are three options available, corresponding to each period

  • beresp.ttl
  • beresp.grace
  • beresp.keep

Example:

sub vcl_backend_response {

	# First we set the TTL value for most of the content that needs to be cached
	set beresp.ttl = 10m;
	set beresp.grace = 2h;

	# Now we can set specific TTLs based on the content to be cached
	# For VoD, we set a medium-long TTL and a long grace period, since VoD
	# content is not prone to change. This allows us to use this cache
	# for the most requested content

	if (beresp.url ~ "/vod") {
		set beresp.ttl = 30m;
		set beresp.grace = 24h;
	}

	# For live content we use a very low TTL and an even smaller grace period
	# since the live content is no longer *live* once it has been consumed
	
	if (beresp.url ~ "/url") {
		set beresp.ttl = 10s;
		set beresp.grace = 2s;
	}
	
	# We are increasing the *keep* duration for IMS

	if (bereq.http.If-Modified-Since) {
		set beresp.keep = 10m;
	}
}

As you can see from the example, suffixes are used:

  • ms - milliseconds
  • s - seconds
  • m - minutes
  • h - hours
  • d - days
  • w - weeks
  • y - years

Additional Information:

How to prevent Varnish from creating new cache for different browsers

If the web server sends the HTTP header

Vary: User-Agent

Varnish then creates new pages for each browser version. That is, different cache entries will be created for Chrome 85 and Chrome 86! Apache sends this HTTP header by default.

Let's demonstrate this.

First, let's make a request to the website using port 8080 (that is, bypassing the cache, we connect directly to Apache):

curl -I 'http://w-e-b.site:8080/?act=all-country-ip&city=Pattaya'

Pay attention to the line:

Vary: User-Agent,Accept-Encoding

There may be other options, for example:

Vary: User-Agent

Now we will run the command twice

time curl -s 'https://w-e-b.site/?act=all-country-ip&city=Pattaya' -A 'Chrome' > /dev/null

In it, we measure the time and can make sure that the second time the cache is created, the time it takes to get the page is much shorter. We also specified Chrome as the User Agent.

But if you change the User Agent value, then you can see from the time spent that the cache is being re-created:

time curl -s 'https://w-e-b.site/?act=all-country-ip&city=Pattaya' -A 'Firefox' > /dev/null

This behavior of the caching system usually doesn't make sense. Therefore, you need to make it so that Varnish uses the same cache for all User Agents.

There are several ways to do this. The easiest is to change the web server settings so that it does not send the “Vary: User-Agent” HTTP header.

The following shows how to change Apache settings so that it doesn't send “Vary: User-Agent”.

On Debian and derivatives:

a2enmod headers

Then add the line to the configuration file /etc/apache2/apache2.conf:

Header set Vary "Accept-Encoding"

Reboot the server:

systemctl restart apache2

On Arch Linux and derivatives:

Make sure to uncomment the following line in /etc/httpd/conf/httpd.conf:

LoadModule headers_module modules/mod_headers.so

Then add the line to the same file (/etc/httpd/conf/httpd.conf):

Header set Vary "Accept-Encoding"

Reboot the server for the changes to take effect:

systemctl restart httpd.service

We have rewritten the Vary HTTP header to only have Accept-Encoding.

This setup is definitely worth the effort! Varnish will now have one cache for all web browsers.

Additional Information:

A 403 page got into the Varnish cache and now it is shown to all users

It may happen that a user who is prohibited from viewing the site (banned by IP or by User Agent) opened a page and it got into the cache. As a result, now all users will be shown a message that access is denied instead of the normal page.

To fix this, add the following setting:

sub vcl_backend_response {	
	if (beresp.status == 403 || beresp.status == 404 || beresp.status >= 500)
	{
		set beresp.ttl = 3s;
	}
}

How to make Apache logs show real IP address instead of 127.0.0.1 when used with Varnish

Since Apache is now receiving requests from Varnish, now the web server logs always show 127.0.0.1 as client IP addresses.

This can be fixed as follows:

  • We tell Varnish to add the X-Forwarded-For HTTP header containing the user's real IP address when sending requests to the Apache server.
  • And in Apache, we enable the mod_remoteip module and specify in the settings to use the IP address from the X-Forwarded-For HTTP header as the user's real IP address

That is, you need to configure both Varnish and Apache. But the setup is very useful and well worth it!

Let's start by configuring Varnish, add to its config file:

sub vcl_recv {
    if (req.restarts == 0) {
        if (req.http.X-Forwarded-For) {
           set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip;
       } else {
        set req.http.X-Forwarded-For = client.ip;
       }
    }
}

The web server settings differ slightly depending on the distribution.

On Debian and derivatives:

a2enmod remoteip

Then add the line to the configuration file /etc/apache2/apache2.conf:

RemoteIPHeader x-forwarded-for

Reboot the web server:

systemctl restart apache2

On Arch Linux and derivatives:

Make sure to uncomment the following line in /etc/httpd/conf/httpd.conf:

LoadModule remoteip_module modules/mod_remoteip.so

Then add the line to the same file:

RemoteIPHeader x-forwarded-for

Reboot the server for the changes to take effect:

systemctl restart httpd.service

Additional Information:

Some tutorials advise you to modify the Apache log format - this will also work if done correctly, but it will take longer.

How to delete cookies that prevent caching

Requests that send cookies are not cached. If you have ad units or metrics (counters) on your site, then we can say that Varnish does not cache anything. Moreover, in the case of cookies for ad networks and counters, this is also absolutely useless data for the server.

To remove all cookies and allow data to be cached add:

sub vcl_recv {
	unset req.http.Cookie;
}

This setting will disrupt sites that rely on cookies. For example, if you have a WordPress site with registration for users, then cookies are required to identify users. In such cases, it is better to use another solution, such as Memcached.

How to exclude certain pages from caching

To exclude from caching all paths containing the string “/path/for/exclude/” anywhere in the URL:

sub vcl_recv {
	if (req.url ~ "^/path/for/exclude/") {
		return (pass);
	}
}

Note that the ~ (tilde) character means that the search is performed using a regular expression. And the ^ (caret) character means the beginning of a line.

If you want to exclude URLs in which “/path/for/exclude/” appears in any part of the URL, then remove the ^ character, for example:

sub vcl_recv {
	if (req.url ~ "/path/for/exclude/") {
		return (pass);
	}
}

If you want the search to be performed not by a regular expression, but by an exact match, then replace ~ with ==, for example:

sub vcl_recv {
	if (req.url == "/path/for/exclude/") {
		return (pass);
	}
}

You can use the if () {} construct several times or combine them into one. Symbol || means logical “OR”:

sub vcl_recv {
	if (req.url ~ "myip" || req.url ~ "proxy-checker" || req.url ~ "my-user-agent") {
		return (pass);
	}
}

That is, the previous setting will exclude from caching all pages with the string “myip” or the string “proxy-checker” or the string “my-user-agent” anywhere in the URL.

An example in which, for the host suip.biz, pages containing the string “/ru” in the URL are excluded from the cache:

sub vcl_recv {
	if (req.http.host == "suip.biz" && req.url == "/ru") {
		return (pass);
	}
}

How to exclude the home page from caching

The following example excludes the home page from the cache for the host suip.biz:

sub vcl_recv {
	if (req.http.host == "suip.biz" && req.url == "/") {
		return (pass);
	}
}

How to increase the size of the Varnish cache

The cache size settings must be changed in the command launch line, for this:

systemctl edit --full varnish

To resize the in-memory cache, edit the -s option. By the way, malloc means that the cache is stored in RAM. You can specify to store it in a file - if you need it, then refer to the documentation.

Specify the desired cache size, for example -s malloc,1400m.

Restart the varnish service for the changes to take effect:

systemctl restart varnish

How to increase connection timeout in Varnish

If the sending of data from Varnish to the client is not complete within 60 seconds, the connection is dropped. For regular sites this is fine, but for video portals or long-term services it may not be enough.

Varnish has quite a few timeout parameters, you can view their value with the command:

varnishadm param.show | grep timeout

Output example:

backend_idle_timeout          60.000 [seconds] (default)
between_bytes_timeout         60.000 [seconds] (default)
cli_timeout                   60.000 [seconds] (default)
connect_timeout               3.500 [seconds] (default)
first_byte_timeout            60.000 [seconds] (default)
idle_send_timeout             60.000 [seconds] (default)
pipe_timeout                  60.000 [seconds] (default)
send_timeout                  60.000 [seconds] (default)
thread_pool_timeout           300.000 [seconds] (default)
timeout_idle                  5.000 [seconds] (default)
timeout_linger                0.050 [seconds] (default)

The parameter we need, which is responsible for the maximum time for sending data during one connection, is called send_timeout.

To change it, you need to edit the command line

systemctl edit --full varnish

Add an option to the command like this:

-p send_timeout=SECONDS

For example, to set a connection timeout for 10 minutes:

-p send_timeout=600

Please note that you cannot specify the “s” suffix or any other, otherwise the program will not start. You only need to specify a number that means seconds for the connection timeout.

With this setting, we changed the value of the maximum time for sending data. But there is another timeout that sets the maximum connection duration. To edit it, open the /etc/varnish/default.vcl file and add the settings there:

backend default {
	.connect_timeout = 600s;
	.first_byte_timeout = 600s;
	.between_bytes_timeout = 600s;
}

In order not to edit the service start options, I tried to add the send_timeout option to the config file, but in this case, the service does not start due to an error. If you know what the matter is and how to do without adding an option in the command line, then write in the comments.

Restart the varnish service for the changes to take effect:

systemctl restart varnish

Additional Information:

How to exclude a specific site from Varnish caching

Exception from hashing softocracy.ru:

sub vcl_recv {
   if (req.http.host ~ "(www\.)?softocracy\.ru") {
     return(pass);
   }
}

If you do not want any site to be cached, then exclude it from caching entirely. In the example above, change softocracy.ru to the site's domain, which should not be cached.

How to cache only a specific domain in Varnish

For all other domains, pass must be returned:

sub vcl_recv {
	# if it's any domain other than example.com, then skip caching
	if (! req.http.host ~ "(www\.)?example\.com") {
		return (pass);
	}
	# otherwise switch to default behavior
}

pass tells Varnish not to look into its cache, it will always receive content from the destination web server.

How to redirect HTTP to HTTPS in Varnish

If you use Varnish, it is no longer possible to redirect to HTTPS using the web server methods, since Apache no longer works with HTTPS connections and does not even listen on port 443.

The following example will show you how to configure Varnish to redirect all requests to suip.biz from HTTP to HTTPS.

import std;

sub vcl_recv {
	# We ask Varnish to give 750 status for HTTP requests from external IP to port 80,
	# but not with SSL Termination Proxy (Hitch).
	if ((client.ip != "127.0.0.1" && std.port(server.ip) == 80) && (req.http.host ~ "^(?i)(www\.)?suip.biz")) {
		set req.http.x-redir = "https://" + req.http.host + req.url;
		return (synth(750, ""));
	}
}


sub vcl_synth {
	# Listen to 750 status from vcl_recv.
	if (resp.status == 750) {
		// Redirect to HTTPS with a 301 status.
		set resp.status = 301;
		set resp.http.Location = req.http.x-redir;
		return(deliver);
	}
}

In the previous configuration example, replace the “suip.biz” domain with your own.

How to delete cookies from all hosts except pages of a specific host

If you want cookies to be deleted for pages of all hosts, except for the pages of a specific host, then use the setting like this:

sub vcl_recv {
	if (! req.http.host ~ "(www\.)?HERE\.DOMAIN") {
		unset req.http.Cookie;
	}
}

Instead of “HERE\.DOMAIN” enter the domain on which you do not need to delete cookies. Note the escaping of the point.

An example of a setting that deletes cookies from all domains, except for the pages of the domains wxmaxima.ru and softocracy.ru:

sub vcl_recv {
	if (! req.http.host ~ "(www\.)?wxmaxima\.ru" && ! req.http.host ~ "(www\.)?softocracy\.ru") {
		unset req.http.Cookie;
	}
}

Attention:

1. Restart the varnish service for the changes to take effect:

systemctl restart varnish

2. In the config file use “unset req.http.Cookie;” only once! If you use it two or more times, the behavior will not be what you expect. Group all the conditions you need using logical AND and OR before using “unset req.http.Cookie;” only.

How to remove cookies from all pages except specific URLs

If you want to exclude only certain pages from deleting cookies, then use the setting like this:

sub vcl_recv {
	if (! req.url ~ "^/PATH/FOR/EXCLUDE/") {
		unset req.http.Cookie;
	}
}

An example of a setting that deletes cookies from all domains, except for the pages of the wxmaxima.ru domains and pages on any domains whose URL contains the string “phpmyadmin”:

sub vcl_recv {
	if (! req.http.host ~ "(www\.)?wxmaxima\.ru" && ! req.url ~ "^/phpmyadmin") {
		unset req.http.Cookie;
	}
}

Attention:

1. Restart the varnish service for the changes to take effect:

systemctl restart varnish

2. In the config file use “unset req.http.Cookie;” only once! If you use it two or more times, the behavior will not be what you expect. Group all the conditions you need using logical AND and OR before using “unset req.http.Cookie;” only.

Adding and Removing HTTP Headers

Varnish Cache gives you the ability to modify, add, and remove HTTP headers for the request and response object.

Request headers

The vcl_recv subroutine is called at the beginning of the request, and this is where we will change the request headers. We will add a hello header with the value world and remove the user agent header.

sub vcl_recv {
	...

	set req.http.hello = "world";
	unset req.http.user-agent;

	...
}

The req.http object is for accessing any request header and is readable only from vcl_recv and vcl_deliver.

Response headers

vcl_backend_response is called when Varnish Cache receives response headers from the upstream service. We will change the header cache control and set it to “public, max-age=600”, and remove the server header.

sub vcl_backend_response {
	...

	set beresp.http.cache-control = "public, max-age=600";
	unset beresp.http.server;

	...
}

The beresp.http object is for accessing any response header and is readable only from vcl_backend_response and vcl_deliver.

Additional documentation:

Loading...
X