Serving Static Content

Всем привет! Сегодняшний урок посвящен теме,без которой практически невозможно начать разработку сайта — это настройка web-сервера и виртуальных хостов. В качестве операционной системе мы будем использовать Ubuntu, а web-сервера — nginx. 

Configure NGINX and NGINX Plus to serve static content, with type-specific root directories, checks for file existence, and performance optimizations.

This section describes how to configure NGINX and NGINX Plus to serve static content, how to define which paths are searched to find requested files, how to set up index files, and how to tune NGINX and NGINX Plus, as well as the kernel, for optimal performance.

Я установил Nginx, используя Ansible. Для установки на Centos7 я использовал пакет yum, чтобы он по умолчанию запускался от имени пользователя root. Я хочу, чтобы он запускался и работал от имени другого пользователя (бывшего пользователя nginx) в окне Centos. Когда я пытаюсь запустить его с другим пользователем, я получаю следующую ошибку:

Не удалось выполнить задание для nginx.service, поскольку процесс управления завершился с кодом ошибки. Смотрите «systemctl status nginx.service» и «journalctl -xe» для подробностей.

Я знаю, что не рекомендуется запускать от имени пользователя root. Итак, как мне обойти это и запустить nginx как пользователь без полномочий root. Спасибо

Configure NGINX and NGINX Plus as a web server, with support for virtual server multi-tenancy, URI and response rewriting, variables, and error handling.

  • Setting Up Virtual Servers
  • Configuring Locations
  • Using Variables
  • Returning Specific Status Codes
  • Rewriting URIs in Requests
  • Rewriting HTTP Responses
  • Handling Errors

For additional information on how to tune NGINX Plus and NGINX Open Source, watch our free webinar on-demand Installing and Tuning NGINX.

Note: The information in this article applies to both NGINX Open Source and NGINX Plus. For ease of reading, the remainder of the article refers to NGINX Plus only.

Each virtual server for HTTP traffic defines special configuration instances called locations that control processing of specific sets of URIs. Each location defines its own scenario of what happens to requests that are mapped to this location. NGINX Plus provides full control over this process. Each location can proxy the request or return a file. In addition, the URI can be modified, so that the request is redirected to another location or virtual server. Also, a specific error code can be returned and you can configure a specific page to correspond to each error code.

Job for nginx.service failed because the control process exited with
error code. See «systemctl status nginx.service» and «journalctl -xe»
for details.

Roald Nefs's user avatar

asked Feb 19, 2017 at 15:47

Sarith's user avatar

user nginx;

This way only master process runs as root. Because: Only root processes can listen to ports below 1024. A webserver typically runs at port 80 and/or 443. That means it needs to be started as root.

Note from the documentation on master and worker processes:

The main purpose of the master process is to read and evaluate
configuration files, as well as maintain the worker processes.

The worker processes do the actual processing of requests.

  • error_log
  • access_log
  • pid
  • client_body_temp_path
  • fastcgi_temp_path
  • proxy_temp_path
  • scgi_temp_path
  • uwsgi_temp_path

Nagev's user avatar

4 gold badges57 silver badges67 bronze badges

answered Feb 19, 2017 at 16:10

Farhad Farahi's user avatar

Farhad Farahi

7 gold badges73 silver badges69 bronze badges

I use a minimal config file like this:

worker_processes 1;
error_log stderr;
daemon off;

events {
  worker_connections  1024;

http {
  include             /etc/nginx/mime.types;
  default_type        application/octet-stream;

  sendfile on;

  keepalive_timeout   65;

  ssl_protocols TLSv1 TLSv1.1 TLSv1.2; 
  ssl_prefer_server_ciphers on;
  access_log access.log;
  server {
    listen            8080;
    server_name       localhost;

    location / {
      include /etc/nginx/uwsgi_params;
      uwsgi_pass localhost:8081;

and I start the process with:

/usr/sbin/nginx -c nginx.conf -p $PWD

answered Jul 25, 2018 at 10:33

David Douard's user avatar

    error_log /tmp/error.log;
    pid       /tmp/;
    events {
      # No special events for this simple setup
    http {
      server {
        listen       8088;
        server_name  localhost;
        # Set a number of log, temp and cache file options that will otherwise
        # default to restricted locations accessible only to root.
        access_log /tmp/nginx_host.access.log;
        client_body_temp_path /tmp/client_body;
        fastcgi_temp_path /tmp/fastcgi_temp;
        proxy_temp_path /tmp/proxy_temp;
        scgi_temp_path /tmp/scgi_temp;
        uwsgi_temp_path /tmp/uwsgi_temp;
        # Serve local files
        location / {
          root /home/<your_user>/web;
          index  index.html index.htm;
          try_files $uri $uri/ /index.html;

answered Jul 3, 2020 at 9:02

OleDahle's user avatar

2 silver badges8 bronze badges

Why not use the rootless bitnami/nginx image:

$ docker run --name nginx bitnami/nginx:latest
  • More info
$ docker exec -it nginx id
uid=1**8 gid=0(root) groups=0(root)

And to verify that Nginx isn’t listening to a root-restricted port 443 even internally:

$ docker ps -a | grep nginx
2453b37a9084   bitnami/nginx:latest                       "/opt/bitnami/script…"   4 minutes ago    Up 30 seconds                 8080/tcp,>8443/tcp                  jenkins_nginx

It’s easy to configure (see docs) and runs even under random UIDs defined at run time (i.e. not hard-coded in the Dockerfile). In fact this is Bitnami’s policy to have all their containers rootless and prepared for UID changes at runtime, which is why we’ve been using them for a few years now under very security-conscious Openshift 3.x (bitnami/nginx in particular as a reverse proxy needed to enable authentication to MLflow web app).

answered Apr 23, 2021 at 19:33

mirekphd's user avatar

3 gold badges37 silver badges58 bronze badges

  1. Update the /etc/nginx/nginx.conf file to give it read permission (644).

Disclaimer: Ensure that in the /etc/nginx/sites-enabled/default
listen is on a non-privileged port.

  • Master process should now be running as your ‘said user’.

answered Apr 18 at 15:49

Titus Cheserem's user avatar

I have worked with Apache before, so I am aware that the default public web root is typically /var/www/.

I recently started working with nginx, but I can’t seem to find the default public web root.

Where can I find the default public web root for nginx?

user456584's user avatar

15 gold badges75 silver badges107 bronze badges

asked May 20, 2012 at 15:46

Might try in /var/www/html/index.nginx-debian.html too.

t56k's user avatar

9 gold badges49 silver badges115 bronze badges

answered Jan 7, 2013 at 14:04

Lufix's user avatar

2 gold badges12 silver badges2 bronze badges

If your configuration does not include a root /some/absolute/path; statement, or it includes one that uses a relative path like root some/relative/path;, then the resulting path depends on compile-time options.

Probably the only case that would allow you to make an educated guess as to what this means for you would be, if you downloaded and compiled the source yourself. In that case, the paths would be relative to whatever --prefix was used. If you didn’t change it, it defaults to /usr/local/nginx. You can find the parameters nginx was compiled with via nginx -V, it lists --prefix as the first one.

Since the root directive defaults to html, this would, of course, result in /usr/local/nginx/html being the answer to your question.

However, if you installed nginx in any other way, all bets are off. Your distribution might use entirely different default paths. Learning to figure out what kind of defaults your distribution of choice uses for things is another task entirely.

answered Jun 20, 2012 at 20:59

Gnarfoz's user avatar

1 gold badge17 silver badges15 bronze badges

The default Nginx directory on Debian is /var/www/nginx-default.

You can check the file: /etc/nginx/sites-enabled/default

server {
        listen   80 default;
        server_name  localhost;

        access_log  /var/log/nginx/localhost.access.log;

        location / {
                root   /var/www/nginx-default;
                index  index.html index.htm;

The root is the default location.

Maroun's user avatar

30 gold badges187 silver badges240 bronze badges

answered Aug 27, 2013 at 14:42

Babistalikesflyingonrails's user avatar

‘default public web root’ can be found from nginx -V output:

nginx -V
nginx version: nginx/1.10.1
built with OpenSSL 1.0.2h  3 May 2016
TLS SNI support enabled
configure arguments: --prefix=/var/lib/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --pid-path=/run/nginx/ --lock-path=/run/nginx/nginx.lock --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --user=nginx --group=nginx --with-ipv6 --with-file-aio --with-pcre-jit --with-http_dav_module --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_v2_module --with-http_auth_request_module --with-mail --with-mail_ssl_module

the —prefix value is the answer to the question. for the sample above the root is /var/lib/nginx

answered Sep 5, 2016 at 17:06

Serge S's user avatar

Serge S

7 silver badges3 bronze badges

For Ubuntu and docker images:


answered Jan 29, 2018 at 20:18

DimiDak's user avatar

2 gold badges25 silver badges32 bronze badges

On Mac OS X installing nginx with brew makes the default directory:

root html
root /usr/local/var/www/html

There is no html directory so it would have to be created manually.

answered Sep 9, 2015 at 22:45

freegnu's user avatar

7 silver badges11 bronze badges


This is the default path, but you can make yours though.

for example, you can make one like this:

 server {
    listen  80;

root /home_web/site1/public_html/www/;

030's user avatar

12 gold badges77 silver badges123 bronze badges

answered Mar 18, 2014 at 15:20

Digital site's user avatar

Digital site

12 gold badges48 silver badges72 bronze badges

You can simply map nginx’s root folder to the location of your website:

nano /etc/nginx/sites-enabled/default

inside the default file, look for the root in the server tag and change your website’s default folder, e.g. my websites are at /var/www

server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        root /var/www; <-- Here!

When I was evaluating nginx, apache2 and lighttpd, I mapped all of them to my website sitting at /var/www. I found this the best way to evaluate efficiently.

Then you can start/stop the server of your choice and see which performs best.

service apache2 stop
service nginx start

Btw, nginx actually is very fast!

answered Sep 1, 2014 at 11:24

Waqas's user avatar

1 gold badge30 silver badges18 bronze badges

Look into nginx config file to be sure.
This command greps for whatever is configured on your Machine:

cat /etc/nginx/sites-enabled/default |grep "root"

answered Jan 2, 2015 at 10:53

Thamme Gowda's user avatar

Thamme Gowda

5 gold badges49 silver badges56 bronze badges

The default web folder for nginx depends on how you installed it, but normally it’s in these locations:


answered May 20, 2012 at 16:05

Ja͢ck's user avatar

38 gold badges263 silver badges309 bronze badges

Run the command nginx -V and look for the --prefix. Use that entry to locate your default paths.

Mark Chackerian's user avatar

answered Apr 7, 2016 at 14:59

Jack's user avatar

1 silver badge2 bronze badges

Dump the configuration:

$ nginx -T
server {
    location / {
        root   /usr/share/nginx/html;

What you get might be different since it depends on how your nginx was configured/installed.

Update: There’s some confusion on the issue of if/when the -T option was added to nginx. It was documented in the man page by vl-homutov on 2015 June 16, which became part of the v1.9.2 release. It’s even mentioned in the release notes. The -T option has been present in every nginx release since, including the one available on Ubuntu 16.04.1 LTS:

root@23cc8e58640e:/# nginx -h    
nginx version: nginx/1.10.0 (Ubuntu)
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]

  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/share/nginx/)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file

answered Sep 9, 2015 at 19:35

rubicks's user avatar

1 gold badge30 silver badges40 bronze badges

On Mac install nginx with brew:

location / { 
    root   html;  # **means /usr/local/Cellar/nginx/1.8.0/html and it soft linked to /usr/local/var/www**
    index  index.html;

JJD's user avatar

60 gold badges203 silver badges339 bronze badges

answered Dec 25, 2015 at 2:25

user2413075's user avatar

answered Dec 15, 2017 at 14:53

MucaP's user avatar

1 gold badge10 silver badges18 bronze badges

you can try to find by performing a search

find / -name html

answered Sep 4, 2015 at 1:44

Eduardo Dennis's user avatar

Eduardo Dennis

13 gold badges81 silver badges105 bronze badges

For AWS EC2 Linux you will find here:


Roman Marusyk's user avatar

24 gold badges72 silver badges115 bronze badges

answered Nov 24, 2016 at 6:58

Vivek Sharma's user avatar

You should now put your content in a location of your choice and edit the root configuration directive in the nginx configuration file /etc/nginx/nginx.conf

answered Feb 5, 2014 at 12:01

jboles's user avatar

2 silver badges4 bronze badges

yusuf@yusuf-he:/usr/share/nginx/html$ pwd

answered Jan 1, 2017 at 12:44

Yusuf Ibrahim's user avatar

Yusuf Ibrahim

5 gold badges21 silver badges46 bronze badges

find / -name nginx

answered Jun 15, 2018 at 4:48

Dylan B's user avatar

Dylan B

8 silver badges16 bronze badges

*default pages web allocated in var/www/html
*default configuration server etc/nginx/sites/avaliable/nginx.conf

server {

    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    index index.html index.php;

    server_name _;

    location /data/ {
        autoindex on;

    location /Maxtor {
        root /media/odroid/;
        autoindex on;


        # This option is important for using PHP.
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;

*default configuracion server etc/nginx/nginx.conf

user www-data;
worker_processes 8;
pid /run/;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;

http {

    # Basic Settings

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # SSL Settings

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    # Logging Settings

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Gzip Settings

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # Virtual Host Configs

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

#mail {
#   # See sample authentication script at:
#   #
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }

answered Jul 16, 2019 at 18:22

Дополнительно:  Где можно получить root-доступ для 64-гигабайтного Samsung Galaxy Note 8?

user11793803's user avatar

If you need to find out nginx public root folder that was defined at compile time you can just check your access.log file.

  1. Open nginx.conf
  2. Find the log_format directive
  3. The value of the log_format is a template string that is used to write information to the access.log file. You can add $document_root variable to this template string to log default www root location to a file.

Here is an example from the http section of nginx.conf with modified log_format directive, $document_root is added at the beginning of the string:

    http {
        include       /etc/nginx/mime.types;
        default_type  application/octet-stream;

                  ## ADD $document_root HERE ##
        log_format  main  '$document_root $remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for"';

        access_log  /var/log/nginx/access.log  main;

        etc. .......
  1. server{
        listen 80;
        server_name localhost;
    1. Reload nginx configuration: nginx -s reload

    2. Send GET request to http://localhost: curl http://localhost

    3. Check the last string of access.log:tail -n 1 /var/log/nginx/access.log

Here is the sample output of this command, where /etc/nginx/html is the default document root defined at compile time :

    /etc/nginx/html - - [15/Mar/2017:17:12:25 +0200] "GET / HTTP/1.1" 404 169 "-" "curl/7.35.0" "-"

answered Mar 15, 2017 at 16:18

G.Denis's user avatar

you can access file config nginx,you can see root /path. in this
default of nginx apache at /var/www/html

Roman Marusyk's user avatar

24 gold badges72 silver badges115 bronze badges

answered Mar 11, 2017 at 2:36

tomnyson's user avatar

1 silver badge6 bronze badges

My nginx on Ubuntu is «nginx version: nginx/1.9.12 (Ubuntu)»
and root path is /var/www/html/

Actually, if you just installed nginx on Ubuntu, then you can go to «/etc/nginx/sites-available» and check the default file, there is a configuration like «root /web/root/path/goes/here». And that is what you are looking for.

answered Oct 19, 2016 at 9:00

Daniel Dong's user avatar

Roman Marusyk's user avatar

24 gold badges72 silver badges115 bronze badges

answered Apr 13, 2018 at 6:29

Syed Abdul Qadeer's user avatar

answered Jul 6, 2018 at 9:14

gokul kandasamy's user avatar

gokul kandasamy

1 gold badge2 silver badges14 bronze badges

in ubuntu 19.04, we found it on

answered Mar 14, 2019 at 6:01

Arséne's user avatar

For nginx/1.4.6 (Ubuntu)

/etc/nginx$ cat /etc/nginx/sites-available/default | grep -i root
- root /usr/share/nginx/html;

answered Dec 22, 2016 at 2:19

lfender6445's user avatar

11 gold badges118 silver badges99 bronze badges

I also had this issue on Digital Ocean running a WordPress website with nginx.

  1. Modify the /etc/nginx/nginx.conf file with the following:
server {
root /var/www/html;

I then had to sudo service nginx restart

nginx -V command also shows you where your nginx config file is located as well (mine was pointed at /etc/nginx/nginx.conf)

answered Apr 12, 2019 at 16:30

John C's user avatar

The default is related to the prefix option of the configure script when nginx is compiled; here’s some strange sample from Debian:

% nginx -V | & tr ' ' "\n" | fgrep -e path -e prefix

Subsequently, the default value of root is set to the html directory (as per the documentation of the root directive), which happens to be within prefix , as can be verified by looking at the $document_root variable from a simple configuration file:

# printf 'server{listen 4867;return 200 $document_root\\n;}\n' \

# nginx -s reload && curl localhost:4867

However, evil distributions like Debian seem to modify it quite a bit, to keep you extra entertained:

% fgrep -e root -e include /etc/nginx/nginx.conf
    include /etc/nginx/mime.types;
    #include /etc/nginx/naxsi_core.rules;
    #passenger_root /usr;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

% fgrep -e root -e include \
    /etc/nginx/conf.d/*.conf /etc/nginx/sites-enabled/*
/etc/nginx/conf.d/so.10674867.conf:server{listen 4867;return 200 $document_root\n;}
/etc/nginx/sites-enabled/default:   root /usr/share/nginx/www;
/etc/nginx/sites-enabled/default:       # include /etc/nginx/naxsi.rules
/etc/nginx/sites-enabled/default:   #   root /usr/share/nginx/www;
/etc/nginx/sites-enabled/default:   #   include fastcgi_params;
/etc/nginx/sites-enabled/default:   # deny access to .htaccess files, if Apache's document root
/etc/nginx/sites-enabled/default:#  root html;
/etc/nginx/sites-enabled/default:#  root html;

But as you saw with the sample server configuration that would serve its $document_root value over http, configuring nginx is simple enough that you can write your own configuration in a matter of a single line or two, specifying the required root to meet your exact needs.

answered Aug 27, 2017 at 21:08

cnst's user avatar

6 gold badges90 silver badges121 bronze badges

Alpine Linux does not have any default location at all. The file /etc/nginx/conf.d/default.conf says:

# Everything is a 404
location / {
    return 404;

# You may need this to prevent return 404 recursion.
location = /404.html {

Replace those with a line like root /var/www/localhost/htdocs to point to the directory you want. Then sudo service nginx restart to restart.

answered May 13, 2019 at 11:41

Lassi's user avatar

3 gold badges21 silver badges34 bronze badges

Настройка php-fpm

FastCGI Process Manager, «Менеджер процессов FastCGI». Это альтернативная реализация FastCGI режима в PHP с несколькими дополнительными возможностями, которые обычно используются для высоконагруженных сайтов. Настройка fpm делается в файле по следующему адресу:

sudo nano /etc/php/5.6/fpm/pool.d/www.conf

Чтобы воспользоваться поиском в nano, нужно нажать комбинацию горячих клавиш «ctrl+w»


user = www-data
group = www-data
listen = /var/run/php/php5.6-fpm.sock

listen.owner = www-data = www-data
listen.allowed_clients =

Rewriting HTTP Responses

Sometimes you need to rewrite or change the content in an HTTP response, substituting one string for another. You can use the sub_filter directive to define the rewrite to apply. The directive supports variables and chains of substitutions, making more complex changes possible.

For example, you can change absolute links that refer to a server other than the proxy:


Another example changes the scheme from http:// to https:// and replaces the localhost address with the hostname from the request header field. The sub_filter_once directive tells NGINX to apply sub_filter directives consecutively within a location:


Note that the part of the response already modified with the sub_filter is not replaced again if another sub_filter match occurs.

Установка php 5

Пройдя все этапы выше, переходим к установке php. Для начала убедимся, что данной версии у нас нет. Переходим в папку по адресу:

cd /etc/php/

Посмотрите, если видите следующую картину:

5.6/ 7.0/ 7.1/ 

И папка 5.6 не пустая, значит php5.6 версии у вас уже установлена. И устанавливать ее заново уже не нужно. Если же ее нет, то установить можно с помощью следующих команд:

sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get install php5.6 php5.6-fpm php5.6-curl php5.6-common php5.6-mcrypt php5.6-xml php5.6-gd php5.6-mbstring php5.6-mysql php5.6-pdo php5.6-imagick -y

Подобная установка поставит все необходимые библиотеки для успешной работы php на вашем сервере и избавит вас от дальнейшей головной боли.


Добавьте / измените следующее в вашем /etc/nginx/nginx.conf:

user nginx;

Вы должны создать пользователя и предоставить рекурсивные разрешения для каталогов webroot.

Таким образом, только главный процесс запускается как root, Потому что: только корневые процессы могут прослушивать порты ниже 1024. Веб-сервер обычно работает на порте 80 и / или 443. Это означает, что он должен быть запущен от имени пользователя root.

Чтобы запустить мастер-процесс от имени пользователя root:

Измените право собственности на следующее:

  • журнал ошибок
  • access_log
  • ПИД-регулятор
  • client_body_temp_path
  • fastcgi_temp_path
  • proxy_temp_path
  • scgi_temp_path
  • uwsgi_temp_path

Измените директивы listen на порты выше 1024, войдите в систему как нужный пользователь и запустите nginx с помощью nginx -c /path/to/nginx.conf

На всякий случай, если это помогает, для целей тестирования / отладки я иногда запускаю экземпляр nginx в качестве непривилегированного пользователя на своем ноутбуке Debian (stretch).

Я использую минимальный файл конфигурации, как это:

worker_processes 1;
error_log stderr;
daemon off;

events {
  worker_connections  1024;

http {
  include             /etc/nginx/mime.types;
  default_type        application/octet-stream;

  sendfile on;

  keepalive_timeout   65;

  ssl_protocols TLSv1 TLSv1.1 TLSv1.2; 
  ssl_prefer_server_ciphers on;
  access_log access.log;
  server {
    listen            8080;
    server_name       localhost;

    location / {
      include /etc/nginx/uwsgi_params;
      uwsgi_pass localhost:8081;

и я начинаю процесс с:

/usr/sbin/nginx -c nginx.conf -p $PWD

На всякий случай, если это поможет кому-то наткнуться на этот вопрос в 2020 году, вот мой минимальный nginx.conf для запуска веб-сервера на порту 8088, работает для пользователя без полномочий root. Нет необходимости изменять права доступа к файлам! (Проверено на Centos 7.4 с nginx 1.16.1)

    error_log /tmp/error.log;
    pid       /tmp/;
    events {
      # No special events for this simple setup
    http {
      server {
        listen       8088;
        server_name  localhost;
        # Set a number of log, temp and cache file options that will otherwise
        # default to restricted locations accessible only to root.
        access_log /tmp/nginx_host.access.log;
        client_body_temp_path /tmp/client_body;
        fastcgi_temp_path /tmp/fastcgi_temp;
        proxy_temp_path /tmp/proxy_temp;
        scgi_temp_path /tmp/scgi_temp;
        uwsgi_temp_path /tmp/uwsgi_temp;
        # Serve local files
        location / {
          root /home/<your_user>/web;
          index  index.html index.htm;
          try_files $uri $uri/ /index.html;

Почему бы не использовать rootless
bitnami/nginx изображение:

      docker run --name nginx bitnami/nginx:latest
  • Больше информации

Его легко настроить (см. Документацию) и он работает со случайными UID (на самом деле, мы уже несколько лет используем его под очень заботящимся о безопасности Openshift 3.x в качестве обратного прокси перед веб-приложением MLflow.

Минимальное количество изменений для запуска Nginx под пользователем без полномочий root при использовании докера:

  • добавить
    -u ${NON_ROOT_UID} аргумент к
    docker run <args> nginx,
  • внести эти изменения в
    nginx.conf, как задокументировано для официального
    nginx Образ Docker :
      pid        /tmp/;

http {
    client_body_temp_path /tmp/client_temp;
    proxy_temp_path       /tmp/proxy_temp_path;
    fastcgi_temp_path     /tmp/fastcgi_temp;
    uwsgi_temp_path       /tmp/uwsgi_temp;
    scgi_temp_path        /tmp/scgi_temp;

Taxing Rewrites¶

Don’t feel bad here, it’s easy to get confused with regular expressions. In
fact, it’s so easy to do that we should make an effort to keep them neat and
clean. Quite simply, don’t add cruft.


Look at the above. Then back here. Then up, and back here. OK. The first rewrite
captures the full URI minus the first slash. By using the built-in variable
we can effectively avoid doing any capturing or matching at all.

Создание тестовой страницы

Нам необходимо добавить какой-нибудь файл, чтобы создать иллюзию настоящего сайта. Сформировать файл можно через редактор nano. Для этого выполним команду:

sudo nano /var/www/

Внутри редактора, чтобы сохранить файл, нажмите комбинацию «ctrl+o» (буква «о» Олег). Чтобы выйти «ctrl+x»

теперь наполним файл текстом, скопируйте html код:

    <h1>Ура! Вы смогли настроить Virtual Host в nginx!</h1>

Not Using Standard Document Root Locations¶

Some directories in any file system should never be used for hosting data from.
These include and . You should never use these as your
document root.

Doing this leaves you open to a request outside of your expected area returning
private data.

NEVER DO THIS!!! (yes, we have seen this)




FastCGI Path in Script Filename¶


Настройка файла hosts

Теперь остался последний момент. Если вы сейчас введете в адресной строке, то, вероятно, получите ошибку. Но, если настроить файл hosts и указать, что по этому домену он должен отправляться на наш сервер, то сайт заработает. Для этого откроем файл:

sudo nano /etc/hosts

В этом файле вы увидите примерно следующее:       localhost       site.loc

Нам сюда нужно добавить еще одну строчку:

Обязательно обратите внимание, что между IP адресом и Доменным именем должна быть , а не пробел

Теперь можете попробовать зайти на ваш сайт по новому адресному имени и получите такую долгожданную фразу — «Ура! Вы смогли настроить Virtual Host в nginx!» 

Конфигурация виртуального хоста

И, самое главное — конфигурация виртуального хоста. Здесь важно не накосячить, а, иначе, ничего не заработает. Переходите в директорию, где они находятся:

cd /etc/nginx/sites-available/

Существует несколько вариантов создания виртуальных хостов:

  1. Можно под каждый конфиг создать отдельный файл. Важно только не забыть создать символьную ссылку в папке sites-enabled
  2. Занести все конфиги сайтов в один в файл default, и каждый виртуальных хост хранить в конструкции server {} server {} server {}
server {
    charset utf-8;
    client_max_body_size 128M;

    listen 80; ## listen for ipv4
    #listen [::]:80 default_server ipv6only=on; ## listen for ipv6

root /var/www/;
index index.php; access_log /var/log/nginx/; error_log /var/log/nginx/;
location / { # Redirect everything that isn't a real file to index.php try_files $uri $uri/ /index.php$is_args$args; } # uncomment to avoid processing of calls to non-existing static files by Yii #location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ { # try_files $uri =404; #} #error_page 404 /404.html; # deny accessing php files for the /assets directory location ~ ^/assets/.*\.php$ { deny all; } location ~ \.php$ { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; #fastcgi_pass; fastcgi_pass unix:/var/run/php/php5.6-fpm.sock; try_files $uri =404; } location ~* /\. { deny all; } }

В данной настройке нужно обратить внимание на следующие поля:

  • server_name — это доменное имя, после ввода которого в адресную строку, пользователь сможет получить информацию из папки root, о ее настройке ниже
  • root — это директория, в которой хранится сайт
  • access_log и error_log — это логирование всех заходов и ошибок на сайте. Мы указываем путь до файлов
  • fastcgi_pass — Задаёт адрес FastCGI-сервера. Адрес может быть указан в виде доменного имени или IP-адреса, порта.
Дополнительно:  Download CLEO SA APK No root for GTA San andreas[ Cheats For Un-Rooted Android]

Чтобы проверить наличие файла, воспользуйтесь командой:

find / -name php5.6-fpm.sock

После того, как все заполнено, вам нужно перезагрузить сервер и fpm. Делается с помощью следующих команд:

/etc/init.d/nginx restart
/etc/init.d/php5.6-fpm restart

 Если во время перезагрузки произошли какие-нибудь ошибки, то можно запустить команду проверки nginx:

nginx -t

В случае успеха должно быть выдано следующее сообщение:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Виртуальные хосты

Для начала нужно разобраться, что из себя представляет виртуальный хост. Это адресное пространство веб-сервера. Оно нужно для того, чтобы пользователь мог создавать несколько сайтов на своем сервере. Выглядит это примерно так: предположим у вас есть блог, интернет-магазин, сайт-визитка, корпоративный портал. Вы можете создать разные виртуальные хосты под каждый сайт, например:,, local.vizitka, local.korp-portal.

Passing Uncontrolled Requests to PHP¶

Many example NGINX configurations for PHP on the web advocate passing every URI
ending in to the PHP interpreter. Note that this presents a serious
security issue on most PHP setups as it may allow arbitrary code execution by
third parties.

The problem section usually looks like this:


Here, every request ending in will be passed to the FastCGI backend. The
issue with this is that the default PHP configuration tries to guess which file
you want to execute if the full path does not lead to an actual file on the

For instance, if a request is made for /forum/avatar/1232.jpg/file.php which
does not exist but if /forum/avatar/1232.jpg does, the PHP interpreter will
process /forum/avatar/1232.jpg instead. If this contains embedded PHP code,
this code will be executed accordingly.

Options for avoiding this are:

  • Set in . This causes the PHP interpreter to only
    try the literal path given and to stop processing if the file is not found.
  • Ensure that NGINX only passes specific PHP files for execution:

  • Specifically disable the execution of PHP files in any directory containing
    user uploads:

  • Use the directive to filter out the problem condition:

  • Use a nested location to filter out the problem condition:


If this does not work, and you’re running NGINX on a virtual machine in
VirtualBox, it may be sendfile() that is causing the trouble. Simply comment out
the sendfile directive or set it to “off”. The directive is most likely found in
your nginx.conf file.:

Создание директории

Теперь нам нужно создать директорию для виртуального хоста. Это, по сути, будет как файловое хранилище для нашего сайта. Воспользуемся командой:

sudo mkdir -p /var/www/

Обратите внимание на ключ «-p». Это означает следующее: если нет родительской папки, то он ее создает автоматически. Название «» выбрано не случайно. Здесь мы используем реальное доменное имя, и в дальнейшем сможем понимать, где какой сайт находится.

Front Controller Pattern Web Apps¶

“Front Controller Pattern” designs are popular and are used on the many of the most
popular PHP software packages; But a lot of examples are more complex than they need
to be. For Drupal, Joomla, etc., just use this:


Note — the parameter names are different based on the package you’re using. For

  • “q” is the parameter used by Drupal, Joomla, WordPress
  • “page” is used by CMS Made Simple

Some software don’t even need the query string and can read from REQUEST_URI.
For example, WordPress supports this:


If you don’t care about checking for the existence of directories, you can skip
it by removing .

Of course, your mileage may vary and you may require something more complex based on
your needs, but for basic sites, these will work perfectly. You should always
start simple and build from there.

Using a Hostname to Resolve Addresses¶



You should never use a hostname in a listen directive. While this may work, it
will come with a large number of issues. One such issue being that the hostname
may not resolve at boot time or during a service restart. This can cause NGINX
to be unable to bind to the desired TCP socket which will prevent NGINX from
starting at all.

A safer practice is to know the IP address that needs to be bound to and use
that address instead of the hostname. This prevents NGINX from needing to look
up the address and removes dependencies on external and internal resolvers.



Root Directory and Index Files




     ~  {

If a request ends with a slash, NGINX treats it as a request for a directory and tries to find an index file in the directory. The index directive defines the index file’s name (the default value is index.html). To continue with the example, if the request URI is /images/some/path/, NGINX delivers the file /www/data/images/some/path/index.html if it exists. If it does not, NGINX returns HTTP code 404 (Not Found) by default. To configure NGINX to return an automatically generated directory listing instead, include the on parameter to the autoindex directive:


You can list more than one filename in the index directive. NGINX searches for files in the specified order and returns the first one it finds.

     $geo.html  ;

The $geo variable used here is a custom variable set through the geo directive. The value of the variable depends on the client’s IP address.


 ~  {

Here, if the URI in a request is /path/, and /data/path/index.html does not exist but /data/path/index.php does, the internal redirect to /path/index.php is mapped to the second location. As a result, the request is proxied.

Using the Default Document Root¶

NGINX packages that exist in Ubuntu, Debian, or other operating systems, as an
easy-to-install package will often provide a ‘default’ configuration file as
an example of configuration methods, and will often include a document root to
hold a basic HTML file.

You should not use the default document root for any site-critical files. There
is no expectation that the default document root will be left untouched by the
system and there is an extremely high possibility that your site-critical data
may be lost upon updates and upgrades to the NGINX packages for your operating

Multiple Index Directives¶



Returning Specific Status Codes

Some website URIs require immediate return of a response with a specific error or redirect code, for example when a page has been moved temporarily or permanently. The easiest way to do this is to use the return directive. For example:


The first parameter of return is a response code. The optional second parameter can be the URL of a redirect (for codes 301, 302, 303, and 307) or the text to return in the response body. For example:


The return directive can be included in both the location and server contexts.

Config Changes Not Reflected¶

  • In Firefox press Ctrl+Shift+Delete, check Cache, click Clear Now. In
    any other browser, just ask your favorite search engine. Do this after every
    change (unless you know it’s not needed) and you’ll save yourself a lot of
  • Use curl.


Сначала давайте убедимся, установлен ли у вас nginx и какой он версии. Для этого нужно ввести команду:

nginx -v

Если у вас nginx установлен, то ответ будет примерно такой:

nginx version: nginx/1.10.1

Если же ответа не последовало, то, в таком случае, его придется установить. Делается это с помощью следующей команды:

sudo apt-get install -y nginx

опцию «-y» мы используем, чтобы ответить на все вопросы «да», и установка сразу же началась.

Use for ¶

Use instead of .

If you use the directive with , will return the wrong path.

  • ==
  • ==
  • ==
  • ==

And if you use , you should set index using directive, will not work.


My Issue Isn’t Listed¶

You don’t see something in here related to your specific issue. Maybe we didn’t
point you here because of the exact issue you’re experiencing. Don’t skim this
page and assume you were sent here for no reason. You were sent here because
something you did wrong is listed here.

This Guide Says¶

The most frequent issue we see happens when someone attempts to just copy and
paste a configuration snippet from some other guide. Not all guides out there
are wrong, but a scary number of them are.

Using SSLv3 with HTTPS¶

Due to the POODLE vulnerability in SSLv3, it is advised to not use SSLv3 in your
SSL-enabled sites. You can very easily disable SSLv3 with this line and provide
only the TLS protocols instead:


Настройка прав

Скорее всего, после создания папок у вашего сервера не будет доступа на запись в них данных. Очень часто различные CMS или фрэймворки используют системы кэширования и логирования, которые пишут данные в файлы. Если у сервера будут проблемы с правами, то он будет выдавать ошибки, что, согласитесь, не есть хорошо. Чтобы разрешить проблему с правами, нужно поменять пользователя папки, ведь ее мы создавали от пользователя root, а nginx работает от пользователя www-data, чтобы изменить пользователя папки выполним следующую команду:

sudo chown -R www-data:www-data /var/www/

Ключ «-R» означает, что мы выполняем команду рекурсивно на все вложенные папки, что в данном случае очень логично. Бывают еще ситуации, когда нужно дать права на чтение (при моем варианте это не пригодилось), но на всякий случай:

sudo chmod -R 775 /var/www

Вообще, тему с правами на папки я бы советовал почитать отдельно, так как от этого напрямую зависит безопасность сервера. Зачастую хватает просто смены пользователя на папку, а все права внутри приложения (если вы используете готовое коробочное решение) уже давно разрулены.

Using ¶

There is a little page about using statements. It’s called IfIsEvil and you
really should check it out. Let’s take a look at a few uses of that are bad.

Check (If) File Exists¶

Using to ensure a file exists is horrible. It’s mean. If you have any recent
version of NGINX you should look at which just made life much easier.



What we changed is that we try to see if exists without requiring .
Using means that you can test a sequence. If doesn’t exist, try
, if that doesn’t exist try a fallback location.

In this case, if the file exists, serve it. If not, check if that directory
exists. If not, then proceed to serve which you make sure exists.
It’s loaded – but oh-so-simple! This is another instance where you can completely
eliminate If.

Chmod 777¶

NEVER use . It might be one nifty number, but even in testing it’s a sign of
having no clue what you’re doing. Look at the permissions in the whole path and
think through what’s going on.

To easily display all the permissions on a path, you can use:

Configuring Locations

Note: In this guide, the word location refers to a single location context.

There are two types of parameter to the location directive: prefix strings (pathnames) and regular expressions. For a request URI to match a prefix string, it must start with the prefix string.

 ~  {

NGINX Location Priority

To find the location that best matches a URI, NGINX Plus first compares the URI to the locations with a prefix string. It then searches the locations with a regular expression.

Higher priority is given to regular expressions, unless the ^~ modifier is used. Among the prefix strings NGINX Plus selects the most specific one (that is, the longest and most complete string). The exact logic for selecting a location to process a request is given below:

  1. Test the URI against all prefix strings.
  2. The = (equals sign) modifier defines an exact match of the URI and a prefix string. If the exact match is found, the search stops.
  3. If the ^~ (caret-tilde) modifier prepends the longest matching prefix string, the regular expressions are not checked.
  4. Store the longest matching prefix string.
  5. Test the URI against regular expressions.
  6. Stop processing when the first matching regular expression is found and use the corresponding location.
  7. If no regular expression matches, use the location corresponding to the stored prefix string.
Дополнительно:  Полного root доступ

A typical use case for the = modifier is requests for / (forward slash). If requests for / are frequent, specifying = / as the parameter to the location directive speeds up processing, because the search for matches stops after the first comparison.



The root directive specifies the file system path in which to search for the static files to serve. The request URI associated with the location is appended to the path to obtain the full name of the static file to serve. In the example above, in response to a request for , NGINX Plus delivers the file .

The proxy_pass directive passes the request to the proxied server accessed with the configured URL. The response from the proxied server is then passed back to the client. In the example above, all requests with URIs that do not start with /images/ are be passed to the proxied server.

Using the directive with ¶

The symptoms of this are difficult to diagnose: typically, it will appear that
you’ve done everything right and yet you get mysterious 404 errors. Why? well,
turning on debug-level error logging reveals that is appending
onto the path already set with . This is due to a bug in NGINX,
but don’t worry—the workaround is simple! As long as your line is
something like , you can simply delete the
line with no significant adverse effect. Here is an example where you cannot use



The one caveat is that this workaround prevents you from using to avoid
PATH_INFO attacks. See Passing Uncontrolled Requests to PHP above for alternative ways
to mitigate these attacks.

Server Name (If)¶


There are actually three problems here. The first being the . That’s what we
care about now. Why is this bad? Did you read If is Evil? When NGINX receives a
request — no matter what is the subdomain being requested, be it or
just the plain — this directive is always evaluated. Since
you’re requesting NGINX to check for the Host header for every request,
it’s extremely inefficient. You should avoid it. Instead use two
directives like the example below.



Besides making the configuration file easier to read. This approach decreases
NGINX processing requirements. We got rid of the spurious . We’re also using
which doesn’t hardcode the URI scheme you’re using, be it http or

Incorrect context¶

The return directive applies only inside the topmost context it’s defined in. In this example:





Handling Errors


Note that this directive does not mean that the error is returned immediately (the return directive does that), but simply specifies how to treat errors when they occur. The error code can come from a proxied server or occur during processing by NGINX Plus (for example, the 404 results when NGINX Plus can’t find the file requested by the client).

      = ;
        # Set the root directory to search for the file

        # Disable logging of errors related to file existence

        # Make an internal redirect if the file is not found
          = $uri;


The error_page directive instructs NGINX Plus to make an internal redirect when a file is not found. The $uri variable in the final parameter to the error_page directive holds the URI of the current request, which gets passed in the redirect.

For example, if is not found, it is replaced with and a new search for a location starts. As a result, the request ends up in the second location context and is proxied to http://backend/.

The open_file_cache_errors directive prevents writing an error message if a file is not found. This is not necessary here since missing files are correctly handled.

Root inside Location Block¶



Rewrite Missing ¶

Very simply, rewrites are relative unless you tell NGINX that they’re not.
Making a rewrite absolute is simple. Add a scheme.


In the above you will see that all we did was add to the
rewrite. It’s simple, easy, and effective.

Using Variables

You can use variables in the configuration file to have NGINX Plus process requests differently depending on defined circumstances. Variables are named values that are calculated at runtime and are used as parameters to directives. A variable is denoted by the $ (dollar) sign at the beginning of its name. Variables define information based upon NGINX’s state, such as the properties of the request being currently processed.

There are a number of predefined variables, such as the core HTTP variables, and you can define custom variables using the set, map, and geo directives. Most variables are computed at runtime and contain information related to a specific request. For example, $remote_addr contains the client IP address and $uri holds the current URI value.

Optimizing Performance for Serving Content

Loading speed is a crucial factor of serving any content. Making minor optimizations to your NGINX configuration may boost the productivity and help reach optimal performance.

Enabling sendfile

By default, NGINX handles file transmission itself and copies the file into the buffer before sending it. Enabling the sendfile directive eliminates the step of copying the data into the buffer and enables direct copying data from one file descriptor to another. Alternatively, to prevent one fast connection from entirely occupying the worker process, you can use the sendfile_max_chunk directive to limit the amount of data transferred in a single sendfile() call (in this example, to 1 MB):


Enabling tcp_nopush

Use the tcp_nopush directive together with the sendfile on;directive. This enables NGINX to send HTTP response headers in one packet right after the chunk of data has been obtained by sendfile().


Enabling tcp_nodelay

The tcp_nodelay directive allows override of Nagle’s algorithm, originally designed to solve problems with small packets in slow networks. The algorithm consolidates a number of small packets into a larger one and sends the packet with a 200 ms delay. Nowadays, when serving large static files, the data can be sent immediately regardless of the packet size. The delay also affects online applications (ssh, online games, online trading, and so on). By default, the tcp_nodelay directive is set to on which means that the Nagle’s algorithm is disabled. Use this directive only for keepalive connections:


Optimizing the Backlog Queue

One of the important factors is how fast NGINX can handle incoming connections. The general rule is when a connection is established, it is put into the “listen” queue of a listen socket. Under normal load, either the queue is small or there is no queue at all. But under high load, the queue can grow dramatically, resulting in uneven performance, dropped connections, and increased latency.

Displaying the Listen Queue

To display the current listen queue, run this command:

netstat -Lan
Current listen queue sizes (qlen/incqlen/maxqlen)
Listen         Local Address         
0/0/128        *.12345            
10/0/128        *.80       
0/0/128        *.8080
Current listen queue sizes (qlen/incqlen/maxqlen)
Listen         Local Address         
0/0/128        *.12345            
192/0/128        *.80       
0/0/128        *.8080

Tuning the Operating System

Increase the value of the net.core.somaxconn kernel parameter from its default value (128) to a value high enough for a large burst of traffic. In this example, it’s increased to 4096.

  • For FreeBSD, run the command:

    sudo sysctl kern.ipc.somaxconn=4096
    1. Run the command:

      sudo sysctl -w net.core.somaxconn=4096
    2. net.core.somaxconn = 4096

Tuning NGINX

If you set the somaxconn kernel parameter to a value greater than 512, change the backlog parameter to the NGINX listen directive to match:


Секреты в настройке виртуальных хостов

Есть одна хитрость, которую я очень часто использую при создании сайтов. Чтобы все ваши сайты лежали в домашней директории пользователя, можно создать там папку, например: www. Получится что-то следующее:

Чтобы эта папка заработала, нужно создать символьную ссылку на нее:

ln -s /var/www/ /home/mylocalComputer/

Теперь пользователь может управлять сайтами из своей домашней директории.
Опция «-s» — позволяет нам создать символическую ссылку.

В общем, что знал — рассказал. Если у вас остались вопросы — задавайте их в комментариях. Спасибо за прочтение. Надеюсь у вас все получилось 🙂  

Trying Several Options


         $uri ;

The file is specified in the form of the URI, which is processed using the root or alias directives set in the context of the current location or virtual server. In this case, if the file corresponding to the original URI doesn’t exist, NGINX makes an internal redirect to the URI specified by the last parameter, returning /www/data/images/default.gif.

     $uri $uri/ $uri.html =;

In the next example, if neither the original URI nor the URI with the appended trailing slash resolve into an existing file or directory, the request is redirected to the named location which passes it to a proxied server.

     $uri $uri/ ;


Setting Up Virtual Servers

The NGINX Plus configuration file must include at least one server directive to define a virtual server. When NGINX Plus processes a request, it first selects the virtual server that will serve the request.

A virtual server is defined by a server directive in the http context, for example:

        # Server configuration

It is possible to add multiple server directives into the http context to define multiple virtual servers.

The example below shows configuration of a server that listens on IP address and port 8080:

    # Additional server configuration
  1. Exact name
  2. Longest wildcard starting with an asterisk, such as *
  3. Longest wildcard ending with an asterisk, such as mail.*
  4. First matching regular expression (in order of appearance in the configuration file)

If the Host header field does not match a server name, NGINX Plus routes the request to the default server for the port on which the request arrived. The default server is the first one listed in the nginx.conf file, unless you include the default_server parameter to the listen directive to explicitly designate a server as the default.


Proxy Everything¶


Yucky. In this instance, you pass EVERYTHING to PHP. Why? Apache might do this,
but you don’t need to. The try_files directive exists for an amazing reason:
It tries files in a specific order. NGINX can first try to serve the static
content, and if it can’t, it moves on. This means PHP doesn’t get involved at
all. MUCH faster. Especially if you’re serving a 1MB image over PHP a few
thousand times versus serving it directly. Let’s take a look at how to do that.



Easy, right? Check if the requested URI exists and can be served by NGINX. If not,
check if it is a directory that can be served. If not, then pass it to your proxy.
Only when NGINX can’t serve that requested URI directly, your proxy overhead will
get involved.

Consider how many of your requests are for static content (images, css,
javascript, etc.). That’s probably a lot of overhead you just saved.

Rewriting URIs in Requests

A request URI can be modified multiple times during request processing through the use of the rewrite directive, which has one optional and two required parameters. The first (required) parameter is the regular expression that the request URI must match. The second parameter is the URI to substitute for the matching URI. The optional third parameter is a flag that can halt processing of further rewrite directives or send a redirect (code 301 or 302). For example:

     $ $1 ;

You can include multiple rewrite directives in both the server and location contexts. NGINX Plus executes the directives one-by-one in the order they occur. The rewrite directives in a server context are executed once when that context is selected.

After NGINX processes a set of rewriting instructions, it selects a location context according to the new URI. If the selected location contains rewrite directives, they are executed in turn. If the URI matches any of those, a search for the new location starts after all defined rewrite directives are processed.

         $ $1/mp3/$2.mp3 ;
     $ $1/mp3/$2.ra  ;

This example configuration distinguishes between two sets of URIs. URIs such as are changed to . Because of the last flag, the subsequent directives (the second rewrite and the return directive) are skipped but NGINX Plus continues processing the request, which now has a different URI. Similarly, URIs such as are replaced with . If a URI doesn’t match either rewrite directive, NGINX Plus returns the 403 error code to the client.

There are two parameters that interrupt processing of rewrite directives:

  • last – Stops execution of the rewrite directives in the current server or location context, but NGINX Plus searches for locations that match the rewritten URI, and any rewrite directives in the new location are applied (meaning the URI can be changed again).
  • break – Like the break directive, stops processing of rewrite directives in the current context and cancels the search for locations that match the new URI. The rewrite directives in the new location are not executed.
Оцените статью
Master Hi-technology
Добавить комментарий