- nginx
- Contents
- Installation
- Running
- Configuration
- Configuration example
- General configuration
- Processes and connections
- Running under different user
- Server blocks
- Per-user directories
- FastCGI
- PHP implementation
- CGI implementation
- Installation in a chroot
- Create necessary devices
- Create necessary directories
- Populate the chroot
- Modify nginx.service to start chroot
- Tips and tricks
- Running unprivileged using systemd
- PID file
- /var/lib/nginx/*
- Log file and directory permissions
- Alternative script for systemd
- Nginx beautifier
- Better headers management
- Troubleshooting
- Configuration validation
- Accessing local IP redirects to localhost
- Error: The page you are looking for is temporarily unavailable. Please try again later. (502 Bad Gateway)
- Error: No input file specified
- Warning: Could not build optimal types_hash
nginx
nginx (pronounced «engine X»), is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server, written by Igor Sysoev in 2005. nginx is well known for its stability, rich feature set, simple configuration, and low resource consumption.
This article describes how to set up nginx and how to optionally integrate it with PHP via #FastCGI.
Contents
Installation
Install the package nginx-mainline (mainline branch: new features, updates, bugfixes) or nginx (stable branch: major bugfixes only).
Using the mainline branch is recommended. The main reason to use the stable branch is that you are concerned about possible impacts of new features, such as incompatibility with third-party modules or the inadvertent introduction of bugs in new features.
For a chroot-based installation for additional security, see #Installation in a chroot.
Running
The default page served at http://127.0.0.1 is /usr/share/nginx/html/index.html .
Configuration
First steps with nginx are described in the Beginner’s Guide. You can modify the configuration by editing the files in /etc/nginx/ The main configuration file is located at /etc/nginx/nginx.conf .
The examples below cover the most common use cases. It is assumed that you use the default location for documents ( /usr/share/nginx/html ). If that is not the case, substitute your path instead.
Configuration example
General configuration
Processes and connections
You should choose a fitting value for worker_processes . This setting ultimately defines how many connections nginx will accept and how many processors it will be able to make use of. Generally, making it the number of hardware threads in your system is a good start. Alternatively, worker_processes accepts the auto value since versions 1.3.8 and 1.2.5, which will try to autodetect the optimal value (source).
The maximum connections nginx will accept is given by max_clients = worker_processes * worker_connections .
Running under different user
By default, nginx runs the master process as root and worker processes as user http . To run worker processes as another user, change the user directive in nginx.conf :
If the group is omitted, a group whose name equals that of user is used.
Server blocks
It is possible to serve multiple domains using server blocks. These are comparable to «VirtualHosts» in Apache HTTP Server. Also see the upstream examples.
In the example below the server listens for incoming connections on IPv4 and IPv6 ports 80 for two domains, domainname1.dom and domainname2.dom :
Restart nginx.service to apply any changes.
Managing server entries
It is possible to put different server blocks in different files. This allows you to easily enable or disable certain sites.
Create the following directories:
Create a file inside the sites-available directory that contains one or more server blocks:
Append include sites-enabled/*; to the end of the http block:
To enable a site, simply create a symlink:
To disable a site, unlink the active symlink:
Reload/restart nginx.service to enable changes to the sites configuration.
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
OpenSSL provides TLS support and is installed by default on Arch installations.
Create a private key and self-signed certificate. This is adequate for most installations that do not require a CSR:
If you need to create a CSR, follow these instructions instead of the above:
Basic example of /etc/nginx/nginx.conf using TLS:
Restart nginx.service to apply any changes.
Per-user directories
To replicate Apache-style
user URLs to users’
/public_html directories, try the following. (Note: if both rules are used, below, the more-specific PHP rule must come first.)
See #PHP implementation for more information on PHP configuration with nginx .
Restart nginx.service to enable the new configuration.
FastCGI
FastCGI, also FCGI, is a protocol for interfacing interactive programs with a web server. FastCGI is a variation on the earlier Common Gateway Interface (CGI); FastCGI’s main aim is to reduce the overhead associated with interfacing the web server and CGI programs, allowing servers to handle more web page requests at once.
FastCGI technology is introduced into nginx to work with many external tools, e.g. Perl, PHP and Python.
PHP implementation
PHP-FPM is the recommended solution to run as FastCGI server for PHP.
Install php-fpm and make sure PHP has been installed and configured correctly. The main configuration file of PHP-FPM is /etc/php/php-fpm.conf . For basic usage the default configuration should be sufficient.
Finally, enable and start php-fpm.service .
nginx configuration
When serving a PHP web-application, a location for PHP-FPM should to be included in each server block [2], e.g.:
If it is needed to process other extensions with PHP (e.g. .html and .htm):
Non .php extension processing in PHP-FPM should also be explicitly added in /etc/php/php-fpm.d/www.conf :
You might use the common TCP socket, not default,
Unix domain sockets should however be faster.
To enable PHP support for a particular server, simply include the php_fastcgi.conf configuration file:
Test configuration
You need to restart the php-fpm.service and nginx.service units if the configuration has been changed in order to apply changes.
To test the FastCGI implementation, create a new PHP file inside the root folder containing:
Navigate this file inside a browser and you should see the informational page with the current PHP configuration.
CGI implementation
This implementation is needed for CGI applications.
fcgiwrap
Install fcgiwrap . The configuration file is /usr/lib/systemd/system/fcgiwrap.socket . Enable and start fcgiwrap.socket .
Multiple worker threads
If you want to spawn multiple worker threads, it is recommended that you use multiwatch AUR , which will take care of restarting crashed children. You will need to use spawn-fcgi to create the unix socket, as multiwatch seems unable to handle the systemd-created socket, even though fcgiwrap itself does not have any trouble if invoked directly in the unit file.
Copy the unit file from /usr/lib/systemd/system/fcgiwrap.service to /etc/systemd/system/fcgiwrap.service (and the fcgiwrap.socket unit, if present), and modify the ExecStart line to suit your needs. Here is a unit file that uses multiwatch AUR . Make sure fcgiwrap.socket is not started or enabled, because it will conflict with this unit:
Tweak -f 10 to change the number of children that are spawned.
nginx configuration
In /etc/nginx , copy the file fastcgi_params to fcgiwrap_params . In fcgiwrap_params , comment or delete the lines which set SCRIPT_NAME and DOCUMENT_ROOT .
Inside each server block serving a CGI web application should appear a location block similar to:
The default socket file for fcgiwrap is /run/fcgiwrap.sock .
Using fastcgi_param SCRIPT_FILENAME /srv/www/cgi-bin/myscript.cgi is a shortcut alternative to setting DOCUMENT_ROOT and SCRIPT_NAME . If you use SCRIPT_FILENAME , you also will not need to copy fastcgi_params to fcgiwrap_params and comment out the DOCUMENT_ROOT and SCRIPT_NAME lines.
If you keep getting a 502 — bad Gateway error, you should check if your CGI-application first announces the mime-type of the following content. For html this needs to be Content-type: text/html .
If you get 403 errors, make sure that the CGI executable is readable and executable by the http user and that every parent folder is readable by the http user.
Installation in a chroot
Installing nginx in a chroot adds an additional layer of security. For maximum security the chroot should include only the files needed to run the nginx server and all files should have the most restrictive permissions possible, e.g., as much as possible should be owned by root, directories such as /usr/bin should be unreadable and unwriteable, etc.
Arch comes with an http user and group by default which will run the server. The chroot will be in /srv/http .
A perl script to create this jail is available at jail.pl gist. You can either use that or follow the instructions in this article. It expects to be run as root. You will need to uncomment a line before it makes any changes.
Create necessary devices
nginx needs /dev/null , /dev/random , and /dev/urandom . To install these in the chroot create the /dev/ directory and add the devices with mknod. Avoid mounting all of /dev/ to ensure that, even if the chroot is compromised, an attacker must break out of the chroot to access important devices like /dev/sda1 .
Create necessary directories
nginx requires a bunch of files to run properly. Before copying them over, create the folders to store them. This assumes your nginx document root will be /srv/http/www .
Then mount $JAIL/tmp and $JAIL/run as tmpfs’s. The size should be limited to ensure an attacker cannot eat all the RAM.
In order to preserve the mounts across reboots, the following entries should be added to /etc/fstab :
Populate the chroot
First copy over the easy files.
Now copy over required libraries. Use ldd to list them and then copy them all to the correct location. Copying is preferred over hardlinks to ensure that even if an attacker gains write access to the files they cannot destroy or alter the true system files.
For files residing in /usr/lib you may try the following one-liner:
And the following for ld-linux-x86-64.so :
Copy over some miscellaneous but necessary libraries and system files.
Create restricted user/group files for the chroot. This way only the users needed for the chroot to function exist as far as the chroot knows, and none of the system users/groups are leaked to attackers should they gain access to the chroot.
Finally make set very restrictive permissions. As much as possible should be owned by root and set unwritable.
If your server will bind port 80 (or any other port in range 739), give the chrooted executable permission to bind these ports without root.
Modify nginx.service to start chroot
Before modifying the nginx.service unit file, it may be a good idea to copy it to /etc/systemd/system/ since the unit files there take priority over those in /usr/lib/systemd/system/ . This means upgrading nginx would not modify your custom .service file.
The systemd unit must be changed to start up nginx in the chroot, as the http user, and store the pid file in the chroot.
You can now safely get rid of the non-chrooted nginx installation.
If you do not remove the non-chrooted nginx installation, you may want to make sure that the running nginx process is in fact the chrooted one. You can do so by checking where /proc/PID/root symmlinks to. If should link to /srv/http instead of / .
Tips and tricks
Running unprivileged using systemd
Edit nginx.service and set the User and optionally Group options under [Service] :
We can harden the service against ever elevating privileges:
Then we need to ensure that user has access to everything it needs. Follow the subsections below and then start nginx.
Linux does not permit non- root processes to bind to ports below 1024 by default. A port above 1024 can be used:
Or you may grant the nginx process the CAP_NET_BIND_SERVICE capability which will allow it to bind to ports below 1024:
Alternatively, you can use systemd socket activation. In this case, systemd will listen on the ports and, when a connection is made, spawn nginx passing the socket as a file descriptor. This means nginx requires no special capabilities as the socket already exists when it is started. This relies on an internal environment variable that nginx uses for passing sockets [3] and is therefore not officially supported. Instead of setting CapabilityBoundingSet and AmbientCapabilities , edit the service override to set the NGINX environment variable to tell nginx which file descriptors the sockets will be passed as:
There will be one socket per listening port starting at file descriptor 3, so in this example we are telling nginx to expect two sockets. Now create a nginx.socket unit specifying what ports to listen on:
The sockets will be passed in the order defined in this unit, so port 80 will be file descriptor 3 and port 443 will be file descriptor 4. If you previously enabled or started the service, you should now stop it, and enable nginx.socket instead. When your system starts, nginx will not be running, but will be started when you access the website in a browser. With this you can harden the service further; for example, in many cases you can now set PrivateNetwork=True in the service file, blocking nginx from the external network, since the socket created by systemd is sufficient to serve the website over. Note that this will print a warning in the logs of the nginx service: 2020/08/29 19:33:20 [notice] 254#254: using inherited sockets from «3:4;»
PID file
nginx uses /run/nginx.pid by default. We can create a directory that user has write access to and place our PID file in there. An example using systemd-tmpfiles:
Run the configuration:
Edit the PID values based on the original nginx.service :
/var/lib/nginx/*
Some directories under /var/lib/nginx need to be bootstrapped by nginx running as root . It is not necessary to start the whole server to do that, nginx will do it on a simple configuration test. So just run one of those and you are good to go.
Log file and directory permissions
The step of running a configuration test will create a dangling root -owned log. Remove logs in /var/log/nginx to start fresh.
The nginx service user needs write permission to /var/log/nginx . This may require changing permission and/or ownership of this directory on your system.
Alternative script for systemd
On pure systemd you can get advantages of chroot + systemd. [4] Based on set user group and pid with:
the absolute path of the file is /srv/http/etc/nginx/nginx.conf .
It is not necessary to set the default location, nginx loads at default -c /etc/nginx/nginx.conf , but it is a good idea.
Alternatively you can run only ExecStart as chroot with parameter RootDirectoryStartOnly set as yes (see systemd.service(5) ) or start it before mount point as effective or a systemd path (see systemd.path(5) ) is available.
Enable the created nginx.path and change the WantedBy=default.target to WantedBy=nginx.path in /etc/systemd/system/nginx.service .
The PIDFile in unit file allows systemd to monitor process (absolute path required). If it is undesired, you can change to default one-shot type, and delete the reference from the unit file.
Nginx beautifier
nginxbeautifier AUR is a commandline tool used to beautify and format nginx configuration files.
Better headers management
Nginx has a rather unintuitive header management system where headers can only be defined in one context, any other headers are ignored. To remedy this we can install the headers-more-nginx module.
Install the package nginx-mod-headers-more package. This will install the module to /usr/lib/nginx/modules directory.
To load the module add the following to the top of your main nginx configuration file.
Troubleshooting
Configuration validation
Accessing local IP redirects to localhost
Solution from the Arch Linux forum.
In /etc/nginx/nginx.conf locate the server_name localhost line without a # in front of it, and add below:
Default behavior is that nginx redirects any requests to the value given as server_name in the config.
Error: The page you are looking for is temporarily unavailable. Please try again later. (502 Bad Gateway)
This is because the FastCGI server has not been started, or the socket used has wrong permissions.
Try out this answer to fix the 502 error.
In Archlinux, the configuration file mentioned in above link is /etc/php/php-fpm.conf .
Error: No input file specified
1. Verify that variable open_basedir in /etc/php/php.ini contains the correct path specified as root argument in nginx.conf (usually /usr/share/nginx/ ). When using PHP-FPM as FastCGI server for PHP, you may add fastcgi_param PHP_ADMIN_VALUE «open_basedir=$document_root/:/tmp/:/proc/»; in the location block which aims for processing php file in nginx.conf .
2. Another occasion is that, wrong root argument in the location
\.php$ section in nginx.conf . Make sure the root points to the same directory as it in location / in the same server. Or you may just set root as global, do not define it in any location section.
3. Check permissions: e.g. http for user/group, 755 for directories and 644 for files. Remember the entire path to the html directory should have the correct permissions. See File permissions and attributes#Bulk chmod to bulk modify a directory tree.
4. You do not have the SCRIPT_FILENAME containing the full path to your scripts. If the configuration of nginx ( fastcgi_param SCRIPT_FILENAME ) is correct, this kind of error means php failed to load the requested script. Usually it is simply a permissions issue, you can just run php-cgi as root:
or you should create a group and user to start the php-cgi:
5. If you are running php-fpm with chrooted nginx ensure chroot is set correctly within /etc/php-fpm/php-fpm.d/www.conf (or /etc/php-fpm/php-fpm.conf if working on older version)
Warning: Could not build optimal types_hash
When starting the nginx.service , the process might log the message:
To fix this warning, increase the values for these keys inside the http block [5] [6]:
Источник