How To Move Nginx Web Root to New Location on Ubuntu 18.04

How To Move Nginx Web Root to New Location on Ubuntu 18.04 Техника




2 сентября, 2016 12:01 пп

В Ubuntu веб-сервер Nginx по умолчанию хранит файлы в корневом каталоге /var/www/html, который обычно расположен в одной файловой системе вместе с остальными компонентами операционной системы. Но в некоторых ситуациях лучше переместить этот каталог в другое место, например в отдельную смонтированную файловую систему. При обслуживании нескольких веб-сайтов с помощью одного экземпляра Nginx можно поместить каталог document root каждого сайта в отдельный том. Это позволяет масштабировать сервер в соответствии с потребностями конкретного сайта или клиента.

Данное руководство научит вас перемещать корневой каталог Nginx.

Содержание
  1. Требования
  2. 1: Копирование файлов в новый каталог
  3. 2: Настройка Nginx
  4. 3: Перезапуск Nginx
  5. Заключение
  6. Требования
  7. 1: Копирование файлов в новое место
  8. 2: Обновление файлов конфигурации
  9. 3: Перезапуск Nginx
  10. Заключение
  11. Требования
  12. 1: Копирование файлов в новый каталог
  13. 2: Настройка Nginx
  14. 3: Перезапуск Nginx
  15. Заключение
  16. Default Location Directive Setup
  17. Change the Default Nginx Root Location (i. e DocumentRoot)
  18. Define Custom 404 Page Not Found Using Location
  19. Define Multiple Custom 50x Server Errors using Location
  20. Serve Your Website Images from a Custom Location
  21. Exact Match Using = (Equalto Sign) Location Modifier
  22. Case-Sensitive Regular Expression Match Using ~ (Tilde Sign)
  23. Case-InSensitive Regular Expression Match Using ~* (Tilde-Asterisk Sign)
  24. ^~ Best Non RegEx Match (Carat-Tilde Sign)
  25. Nginx Location Related Error Messages
  26. Summary of Location Modifiers
  27. Define Custom Named Location Using @ (At Sign)
  28. Nginx Location Matching Processing Sequence and Logic
  29. Copy or Move NGINX Root Directory Content
  30. Update NGINX configuration
  31. Restart NGINX web server
  32. Related posts:
  33. Root Directory and Index Files
  34. Trying Several Options
  35. Optimizing Performance for Serving Content
  36. Enabling sendfile
  37. Enabling tcp_nopush
  38. Enabling tcp_nodelay
  39. Optimizing the Backlog Queue
  40. Displaying the Listen Queue
  41. Tuning the Operating System
  42. Tuning NGINX
  43. Setting Up Virtual Servers
  44. Configuring Locations
  45. NGINX Location Priority
  46. Using Variables
  47. Returning Specific Status Codes
  48. Rewriting URIs in Requests
  49. Rewriting HTTP Responses
  50. Handling Errors
  51. This Guide Says¶
  52. My Issue Isn’t Listed¶
  53. Chmod 777¶
  54. Root inside Location Block¶
  55. Multiple Index Directives¶
  56. Using ¶
  57. Server Name (If)¶
  58. Check (If) File Exists¶
  59. Front Controller Pattern Web Apps¶
  60. Passing Uncontrolled Requests to PHP¶
  61. FastCGI Path in Script Filename¶
  62. Taxing Rewrites¶
  63. Rewrite Missing ¶
  64. Proxy Everything¶
  65. Use for ¶
  66. Config Changes Not Reflected¶
  67. VirtualBox¶
  68. Not Using Standard Document Root Locations¶
  69. Using the Default Document Root¶
  70. Using a Hostname to Resolve Addresses¶
  71. Using SSLv3 with HTTPS¶
  72. Using the directive with ¶
  73. Incorrect context¶

Требования

  • Предварительно настроенный сервер Ubuntu 16.04.
  • Пользователь с доступом к sudo (о настройке такого пользователя можно узнать здесь).
  • Установленный сервер Nginx (инструкции по установке можно найти в этом мануале).
  • Новое место хранения для document root. Выберите новое местонахождение файлов сайта согласно вашим потребностям. Если вы хотите переместить корневой каталог на другое устройство хранения данных, выберите точку монтирования устройства.

В данном мануале показано, как переместить данные в блочное хранилище, смонтированное в /mnt/volume-nyc1-01. Это поможет вам переместить каталог данных в новое место независимо от того, какое хранилище вы используете.

1: Копирование файлов в новый каталог

Свежая установка Nginx использует в качестве корневого каталога /var/www/html. Однако на старых установках может быть несколько каталогов document root в зависимости от количества виртуальных хостов.

Сначала нужно узнать местонахождение дополнительных корневых каталогов. Чтобы сфокусировать своё внимание только на активных сайтах, выполните поиск по /etc/apache2/sites-enabled. С помощью флага -R команда grep вернёт директиву root и имя файла, в котором она находится:

grep "root" -R /etc/nginx/sites-enabled

На свежей установке сервера вывод будет примерно такой:

/etc/nginx/sites-enabled/default:       root /var/www/html;
/etc/nginx/sites-enabled/default:       # deny access to .htaccess files, if Apache's document root
/etc/nginx/sites-enabled/default:#      root /var/www/example.com;

Выяснив местонахождение корневых каталогов, можно скопировать их на новое устройство с помощью rsync. Флаг –a сохраняет привилегии и другие свойства каталога. Флаг –v предоставляет подробный вывод.

Примечание: Убедитесь, что в названии каталога нет конечной косой черты (которую система может добавить, если вы используете автодополнение). Если такой слеш есть, rsync будет сбрасывать содержимое каталога в точку монтирования, а не в каталог.

sudo rsync -av /var/www/html

2: Настройка Nginx

Nginx использует глобальные и индивидуальные конфигурационные файлы.

Если вы работаете со старой установкой веб-сервера, вам нужно отредактировать все файлы, полученные в выводе grep. В данном примере рассмотрим стандартный конфигурационный файл default.

sudo nano /etc/nginx/sites-enabled/default

Найдите директиву root и укажите в ней новое местонахождение корневого каталога.

Примечание: Путь к корневому каталогу нужно исправить во всех конфигурационных файлах, в которых он упомянут. В старых установках могут использоваться алиасы и переопределения настроек, которые тоже нуждаются в обновлении. Проверьте все файлы, в которых команда grep нашла путь к корневому каталогу.

. . .
# include snippets/snakeoil.conf;
root ;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
. . .

3: Перезапуск Nginx

Проверьте синтаксис на наличие ошибок с помощью команды:

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

Если команда не сообщила об ошибках, можете перезапустить сервер.

sudo systemctl restart nginx

После перезапуска посетите сайты, чьи корневые каталоги вы переместили на новое устройство, и убедитесь, что они работают. После этого можно удалить оригинальный каталог.

sudo rm -Rf /var/www/html

Заключение

Теперь вы знаете, как перемещать корневой каталог Nginx на новое устройство. Это очень полезный навык в управлении веб-сервером, позволяющий без труда разместить несколько сайтов на одном сервере или быстро перейти на новое устройство хранения данных.

Чтобы улучшить производительность сайта с высокой нагрузкой, читайте статью Настройка Nginx с поддержкой HTTP/2 в Ubuntu 16.04.

Tags: ,






25 декабря, 2021 12:01 пп

В системе Ubuntu веб-сервер Nginx хранит свои документы в /var/www/html, который обычно находится в корневой файловой системе вместе с остальной частью операционной системы. Но иногда бывает полезно переместить корневой каталог в другое место — отдельно собранную файловую систему. Например, если вы обслуживаете несколько веб-сайтов из одного экземпляра Nginx, индивидуальное размещение корневого каталога каждого сайта позволяет масштабировать его в соответствии с потребностями этого сайта или клиента.

В данном руководстве вы переместите корневой каталог Nginx на новое место.

Требования

Для следования этому руководству вам понадобятся:

  • Сервер (у нас установлен Ubuntu 20.04) и пользователь без root-полномочий, с доступом sudo. Больше о настройке пользователя с этими полномочиями читайте в нашем руководстве по начальной настройке сервера Ubuntu.
  • Ngnix, установленный в соответствии с руководством по установке Ngnix на Ubuntu
  • Сертификат TLS/SSL. Для этого есть три опции:
    • Вы можете получить бесплатный сертификат от Let’s Encrypt, следуя инструкциям по защите Nginx с помощью Let’s Encrypt.
    • Можете сгенерировать и настроить самоподписанный сертификат, следуя инструкции по созданию SSL-сертификата для Nginx.
    • Купить его у провайдера и настроить на Nginx.
  • Новое место для корнегового каталога вашего сайта. В этом руководстве мы будем использовать каталог /mnt/volume-nyc3-01 в качестве нового местоположения. Новое расположение корневого каталога можно настроить в соответствии с вашими потребностями. Если вы перемещаете корневой каталог на другое устройство хранения, вам нужно выбрать место под точкой монтирования устройства.

Мы будем использовать доменное имя your_domain, но вам следует заменить его вашим доменом

1: Копирование файлов в новое место

В свежей установке Nginx корневой каталог находится в /var/www/html. Однако если вы следовали руководствам, перечисленным в требованиях, вы создали новый корневой каталог, /var/www/your_domain/html. Кроме того, в вашей среде также могут быть и дополнительные корневые каталоги. На этом этапе мы установим расположение корневых каталогов и скопируем соответствующие файлы в их новое расположение.

Найти корневые каталоги можно с помощью grep. Давайте поищем в каталоге /etc/nginx/sites-enabled, сосредоточив внимание только на активных сайтах. Флажок -R гарантирует, что grep выведет и строку с корневой директивой, и полное имя файла:

$ grep -R "root" /etc/nginx/sites-enabled

Если вы работаете на новом сервере и выполнили все мануалы из требований, результат будет выглядеть так:

/etc/nginx/sites-enabled/your_domain:           root /var/www/your_domain/html;
/etc/nginx/sites-enabled/default:               root /var/www/html;
/etc/nginx/sites-enabled/default:               # deny access to .htaccess files, if Apache's document root
/etc/nginx/sites-enabled/default:#              root /var/www/your_domain;

Среда и настройки сервера, с которым вы уже работаете некоторое время, отличаются от среды свежего сервера, потому и результат может отличаться от показанного здесь. В любом случае, вывод grep позволяет убедиться, что вы перемещаете нужные файлы и обновляете соответствующие конфиги.

Теперь, когда местоположение корневого каталога подтверждено, можно скопировать файлы в новое место с помощью rsync. Флаг -a сохраняет привилегии и другие свойства каталога, а -v обеспечивает подробный вывод, чтобы вы могли следить за ходом синхронизации:

$ sudo rsync -av /var/www/your_domain/html /mnt/volume-nyc3-01

Примечание: Убедитесь, что в конце имени каталога нет слеша – он может появиться при использовании автодополнения. Если в конце стоит слеш, rsync будет выгружать содержимое каталога в точку монтирования вместо каталога html.

Вы увидите такой вывод:

sending incremental file list
created directory /mnt/volume-nyc3-01
html/
html/index.html
sent 318 bytes  received 39 bytes  714.00 bytes/sec
total size is 176  speedup is 0.49

Теперь, когда наши файлы на месте, перейдем к конфигурации Ngnix, которая должна отобразить эти изменения.

2: Обновление файлов конфигурации

Nginx использует как глобальные, так и индивидуальные файлы конфигурации. Мы изменим файл серверного блока для проекта your_domain:/etc/nginx/sites-enabled/your_domain.

Примечание: Не забудьте заменить your_domain на ваше доменное имя. И помните, что вы будете изменять файлы server-блоков, которые были в выводе, когда вы запускали команду grep в пункте 1 этого руководства.

Начните с открытия /etc/nginx/sites-enabled/your_domain в редакторе:

$ sudo nano /etc/nginx/sites-enabled/your_domain

Найдите строку, начинающуюся с root, и включите в нее новое расположение корневого каталога. В нашем случае это /mnt/volume-nyc3-01/html.

server {
        root /mnt/volume-nyc3-01/html;        index index.html index.htm index.nginx-debian.html;        . . .
}
. . .

Отследите в файле все места, где встречается исходный корневой путь, выведенный при помощи grep (в том числе в псевдонимах или перезаписываемых файлах). Возможно, вам придется обновить их, чтобы отразить новое расположение корневой папки.

После внесения всех необходимых изменений сохраните и закройте файл.

3: Перезапуск Nginx

Закончив вносить изменения в конфигурацию, вы можете перезапустить Nginx и проверить результаты.

Сначала убедитесь, что синтаксис конфигураций верен:

$ sudo nginx -t

Если всё в порядке, вы увидите вывод:

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

Если проверка прошла успешно, перезапустите Nginx:

$ sudo systemctl restart nginx

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

$ sudo rm -Rf /var/www/your_domain/html

Вы успешно перенесли корневой каталог Nginx на новое место.

Заключение

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

Tags:






12 сентября, 2018 12:23 пп

В Ubuntu веб-сервер Nginx по умолчанию хранит файлы в корневом каталоге /var/www/html, который обычно расположен в одной файловой системе вместе с остальными компонентами операционной системы. Но в некоторых ситуациях лучше переместить этот каталог в другое место, например в отдельную смонтированную файловую систему. При обслуживании нескольких веб-сайтов с помощью одного экземпляра Nginx можно поместить каталог document root каждого сайта в отдельный том. Это позволяет масштабировать сервер в соответствии с потребностями конкретного сайта или клиента.

Данный мануал научит вас перемещать корневой каталог Nginx.

Требования

  • Сервер Ubuntu 18.04, настроенный по этому мануалу.
  • Установленный сервер Nginx (инструкции по установке можно найти в этом мануале).
  • TLS/SSL-сертификат. Если у вас есть домен, вы можете получить бесплатный доверенный сертификат от сервиса Let’s Encrypt. Если у вас пока нет домена, вы можете сгенерировать самоподписанный сертификат. В этом мануале мы используем условный домен example.com.
  • Новое место хранения для document root. Выберите новое расположение файлов сайта согласно вашим потребностям. Если вы хотите переместить корневой каталог на другое устройство хранения данных, выберите точку монтирования устройства. В данном мануале показано, как переместить данные в блочное хранилище, смонтированное в /mnt/volume-nyc1-01. Это поможет вам переместить каталог данных в новое место независимо от того, какое хранилище вы используете.

1: Копирование файлов в новый каталог

Свежая установка Nginx использует в качестве корневого каталога /var/www/html. Однако на старых установках может быть несколько каталогов document root в зависимости от количества виртуальных хостов. Если вы следовали этому мануалу по установке Nginx, ваш корневой каталог находится в /var/www/example.com/html.

Сначала нужно узнать местонахождение дополнительных корневых каталогов. Чтобы сфокусировать своё внимание только на активных сайтах, выполните поиск по /etc/apache2/sites-enabled. С помощью флага -R команда grep вернёт директиву root и имя файла, в котором она находится:

grep -R "root" /etc/nginx/sites-enabled

На свежей установке сервера вывод будет примерно такой:

/etc/nginx/sites-enabled/example.com:           root /var/www/example.com/html;
/etc/nginx/sites-enabled/default:               root /var/www/html;
/etc/nginx/sites-enabled/default:               # deny access to .htaccess files, if Apache's document root
/etc/nginx/sites-enabled/default:#              root /var/www/example.com;

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

Выяснив местонахождение корневых каталогов, можно скопировать их на новое устройство с помощью rsync. Флаг –a сохраняет привилегии и другие свойства каталога. Флаг –v предоставляет подробный вывод.

Дополнительно:  Root ghfdf это

Примечание: Убедитесь, что в названии каталога нет конечной косой черты (которую система может добавить, если вы используете автодополнение). Если такой слеш есть, rsync будет сбрасывать содержимое каталога в точку монтирования, а не в каталог.

sudo rsync -av /var/www/example.com/html /mnt/volume-nyc3-01
sending incremental file list
created directory /mnt/volume-nyc3-01
html/
html/index.html
sent 318 bytes  received 39 bytes  714.00 bytes/sec
total size is 176  speedup is 0.49

2: Настройка Nginx

Nginx использует глобальные и индивидуальные конфигурационные файлы.

Если вы работаете со старой установкой веб-сервера, вам нужно отредактировать все файлы, полученные в выводе grep. В данном примере рассмотрим виртуальный хост проекта example.com.

sudo nano /etc/nginx/sites-enabled/example.com

Найдите директиву root и укажите в ней новое расположение корневого каталога.

Примечание: Путь к корневому каталогу нужно исправить во всех конфигурационных файлах, в которых он упомянут. В старых установках могут использоваться алиасы и переопределения настроек, которые тоже нуждаются в обновлении. Проверьте все файлы, в которых команда grep нашла путь к корневому каталогу.

3: Перезапуск Nginx

Проверьте синтаксис на наличие ошибок с помощью команды:

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

Если команда не сообщила об ошибках, можете перезапустить сервер.

sudo systemctl restart nginx

После перезапуска посетите сайты, чьи корневые каталоги вы переместили на новое устройство, и убедитесь, что они работают. После этого можно удалить оригинальный каталог.

sudo rm -Rf /var/www/example.com/html

Заключение

Теперь вы знаете, как перемещать корневой каталог Nginx на новое устройство. Это очень полезный навык в управлении веб-сервером, позволяющий без труда разместить несколько сайтов на одном сервере или быстро перейти на новое устройство хранения данных.

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

Tags: , ,


Nginx LocationIf you are running Nginx webserver, it is important for you to understand how the location directive works.

Nginx uses location directive to decide what configuration it should apply based on prefix or the pattern in the incoming URL.

For example, from what directory it should serve the image files when an URL ends with *.gif or *.png or any other image filename extension.

  1. Default Location Directive Setup
  2. Change the Default Nginx Root Location (i.e DocumentRoot)
  3. Define Custom 404 Page Not Found Using Location
  4. Define Multiple Custom 50x Server Errors using Location
  5. Serve Your Website Images from a Custom Location
  6. Exact Match Using = (Equalto Sign) Location Modifier
  7. Case-Sensitive Regular Expression Match Using ~ (Tilde Sign)
  8. Case-InSensitive Regular Expression Match Using ~* (Tilde-Asterisk Sign)
  9. ^~ Best Non RegEx Match (Carat-Tilde Sign)
  10. Nginx Location Related Error Messages
  11. Summary of Location Modifiers
  12. Define Custom Named Location Using @ (At Sign)
  13. Nginx Location Matching Processing Sequence and Logic
syntax:
location [modifier] match {
}

In the above syntax:

  • Modifier is optional
  • Match defines what in the URL should be matched to execute the configuration mentioned inside this particular location block.
  • When there is no modifier, the match acts just as a prefix string for the incoming URL
  • If we use ~ or ~* in the modifier, then the match can be a regular expression.

server { listen 80; server_name thegeekstuff.com location / { root /var/www/html; index index.html index.htm; } .. ..
}

You can have as many location directives as you want for your website.

If you are new to Nginx, you can install it as explained in How to Install and Configure Nginx from Source on Linux

Default Location Directive Setup

If you’ve installed Nginx with default configuration, you can view your current location directive values in the default.conf file as shown below.

The main configuration file is: /etc/nginx/nginx.conf.

But, the server and location directive will be in the default.conf file that is located under /etc/nginx/conf.d/default.conf file as shown below.

# vi /etc/nginx/conf.d/default.conf location / { root /usr/share/nginx/html; index index.html index.htm; } location = /50x.html { root /usr/share/nginx/html; }
  • / for the default location
  • /50x.html for all server errors

Change the Default Nginx Root Location (i. e DocumentRoot)

# vi /etc/nginx/conf.d/default.conf location / { root /var/www/html; index index.html index.htm; }

This is the sample file that we created under /var/www/html for this testing.

# cat /var/www/html/index.html
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello World! - New Nginx Root Location</h1>
</body>
</html>

Note: Anytime you modify nginx configuration file, you should restart nginx using systemctl or service command.

But in most cases, instead of restarting it is good enough if you just reload the configuration as shown below.

# service nginx reload
Reloading nginx: [ OK ]

Define Custom 404 Page Not Found Using Location

Using location directive you can also configure the file that should be served when nginx encounters a HTTP 404 error code. i.e File Not Found.

# vi /etc/nginx/conf.d/default.conf error_page 404 /404.html; location = /404.html { root /var/www/html/errors; }

In the above:

  • error_page – Use this directive to define what type of errors you want to capture. Here we are capturing 404 error. The /404.html says that when 404 error is captured, it should display the /404.html page.
  • The location directory then says that this /404.html file should be served from the /var/www/html/errors directory.
  • The = modifier next the to the location directive says that the URL /404.html has to match exactly for this configuration to be applied. Basically it says that this configuration will be effective only for the 404 error code.

Since we’ve customized this directory location, create the errors directory and the 404.html file as shown below.

# mkdir -p /var/www/html/errors
# cat 404.html
<html>
<head>
<title>404 - Where did it go?</title>
</head>
<body>
<h1>File Not Found: Don't worry. We'll find it for you. Please contact us.</h1>
</body>
</html>

Define Multiple Custom 50x Server Errors using Location

In this example, I’ve modified the location of the 50x.html file and created a custom page.

One important thing to note here is that, you can redirect multiple HTTP error codes to a single file. As shown here, any server side error codes (including 500, 502, 503 or 504) will be redirected to one error file called 50x.html.

In this example, we’ve custom created this 50x.html file and placed it under errors directory.

 error_page 500 502 503 504 /50x.html; location = /50x.html { root /var/www/html/errors; }

Next create the 50x.html file in your custom errors directory.

# cd /var/www/html/errors;
# vi 50x.html
<html>
<head>
<title>50x - Server Error</title>
</head>
<body>
<h1>Something went wrong on the server side. Please contact our server admin.</h2>
</body>
</html>

Serve Your Website Images from a Custom Location

Another typical use for a location directive is to specify the directory location from where you like to serve all your website’s image files.

 location /img/ { root /custom/images; }
# ls -1 /custom/images/img/
dog.gif
cat.gif
fish.png
parrot.jpg
..

So, when you call thegeekstuff.com/img/cat.gif, it will server the cat.gif from the above directory.

If you are interested in setting up a loadbalancer, then inside the location directive you should use proxy_pass as explained in How to Setup Nginx as loadbalancer for Apache or Tomcat for HTTP/HTTPS

Exact Match Using = (Equalto Sign) Location Modifier

Use the = (equal-to sign) as a modifier when you want to match the exact request URI.

 location /db { root /data; ... }
  • URL/db – Will look for index.html file under /data/db
  • URL/db/index.html – Will look for index.html file under /data/db
  • URL/db/connect/index.html – Will look for index.html file under /data/db/connect

But, when we add the = (equalto sign) location modifier as shown below, the above behavior will change.

 location = /db { root /data; }
  • URL/db – Will work.
  • URL/db/index.html – Will not work.
  • URL/db/connect/index.html – Will not work.

Important: Also, in the above example, the root value will not be honored. This is because the /db will use the root from the “/” location that was defined earlier. So, when you go to the URL/db, it will really serve the index.html file from /var/www/html/db/ and not from /data/db/ as you would expected.

# ls -l /var/www/html/db/index.html
-rw-r--r--. 1 root root 13 May 8 17:28 /var/www/html/db/index.html

Also, please note that when Nginx matches a particular location directive that has the = modifier, then will not look for any further location directives.

One popular configuration is to setup Nginx as a front-end to your existing Apache/PHP website. For this, you should use reverse proxy as per the instructions from here: How to Setup Nginx Reverse Proxy to Apache/PHP on Linux

Case-Sensitive Regular Expression Match Using ~ (Tilde Sign)

When you want to use regular expression match (instead of prefix match), then you should use ~ (tilde sign).

Using ~ will perform case-sensitive match.

 location ~ .(png|gif|ico|jpg|jpeg)$ { }

In the above:

  • ~ is for case sensitive regular expression match modifier
  • ( ) – all the values inside this regular expression will be considered as keywords in the URL
  • | This is the OR operator. i.e png, or gif, or ico, or jpg, or jpeg keyword in the URL will be considered.
  • $ at the end means that the specified keyword should be at the end of the URL.
  • Basically, the whole regular expression is for any image URL. i.e any URL that ends with an image file.

In this case:

  • URL/img/dog.gif – This will work as we have dog.gif on our server.
  • URL/img/CAT.GIF – This will not work, as we don’t have the upper-case CAT.GIF (we only have lower case cat.gif on the server side). Since we are using ~ which will do a case-sensitive match and will not serve this upper-case CAT.GIF file.

Also, instead of specifying two keywords jpg and jpeg, you can also combine them as shown below using “jpe?g”

 location ~ .(png|gif|ico|jpe?g)$ { }

If you want to match the php keyword in the URL (for php websites) and do something with it, then refer to some of the Location examples from here: How to Add Custom File Extension for PHP in Apache and Nginx

Case-InSensitive Regular Expression Match Using ~* (Tilde-Asterisk Sign)

This is similar to the above example, but this will perform a case-insensitive regular expression matching.

 location ~* .(png|gif|ico|jpg|jpe?g)$ { root /custom; }

In this case:

  • URL/img/dog.gif – This will work as we have dog.gif on our server.
  • URL/img/CAT.GIF – This will also work, as this will be treated as case-insensitive and nginx will serve the cat.git from the server even though the URL has the uppercase CAT.GIF

^~ Best Non RegEx Match (Carat-Tilde Sign)

When this modifier is used, the matching URL will use this configuration. Basically, this configuration will be used as the prefix match, but this will not perform any further regular expression match even if one is available.

location ^~ /img/ {
}
# service nginx start
Starting nginx: nginx: [emerg] duplicate location "/" in /etc/nginx/conf.d/default.conf:45 [FAILED]
# service nginx restart
nginx: [emerg] "location" directive is not allowed here in /etc/nginx/nginx.conf:34
nginx: configuration file /etc/nginx/nginx.conf test failed
 location $ /ab { root /var/www/html1; index index.html index.htm; }
# service nginx restart
nginx: [emerg] invalid location modifier "$" in /etc/nginx/conf.d/default.conf:17
nginx: configuration file /etc/nginx/nginx.conf test failed

Summary of Location Modifiers

location = / {
}
location / {
}
location /db/ {
}
location ^~ /images/ {
}
location ~* .(png|gif|ico|jpg|jpeg)$ {
}

Define Custom Named Location Using @ (At Sign)

  • Use @ to define a named location
  • This location is configured as request redirection. This is not used for regular request processing.
  • You cannot nest the @ location directives
location / { try_files $uri $uri/ @custom;
}
location @custom { rewrite ^/(.+)$ /index.php?_route_=$1 last;
}

In the above example:

  • First, the @custom itself can be defined inside any other location block. As shown in the above example, this is defined in the 1st location block using try_files.
  • Next, the “location @custom” refers to the @custom named location that was defined earlier in any other location block. This custom named location is used in the 2nd location block above.
  • Please note that instead of @custom, you can call it anything you like. For example: @database, @myapp, @complexredirect, @misc, @thegeekstuff

Nginx Location Matching Processing Sequence and Logic

  • First, the incoming URI will be normalized even before any of the location matching takes place. For example, First it will decode the “%XX” values in the URL.
  • It will also resolve the appropriate relative path components in the URL, if there are multiple slashes / in the URL, it will compress them into single slash etc. Only after this initial normalization of the URL, the location matching will come into play.
  • When there is no location modifier, it will just be treated as a prefix string to be matched in the URL.
  • Nginx will first check the matching locations that are defined using the prefix strings.
  • If the URL has multiple location prefix string match, then Nginx will use the longest matching prefix location.
  • After the prefix match, nginx will then check for the regular expression location match in the order in which they are defined in the nginx configuration file.
  • So, the order in which you define the regular expression match in your configuration file is important. The moment nginx matches a regular expression location configuration, it will not look any further. So, use your important critical regular expression location match at the top of your configuration.
  • If there is no regular expression matching location is found, then Nginx will use the previously matched prefix location configuration.

When you migrate your website to new location, you need to change NGINX root directory configuration so that NGINX server can serve requests from the new location. Let’s look at how to move NGINX web root to new location in Ubuntu, as well as CentOS.

Дополнительно:  Синий экран смерти на Windows 10

By default, NGINX webroot is located at /var/www/html. If you need to move your website documents and content to a different location, then you will need to move NGINX default root directory to new location and make your server point to this location. You can use these steps to move NGINX web root to new location in Ubuntu (Debian) as well as CentOS (RPM) systems.

After you move NGINX web root to new location, you may want to use a reporting tool to monitor the key metrics about your website/application such as signups, traffic, sales, revenue, etc. using dashboards & charts, to ensure everything is working well and spot issues quickly.

Copy or Move NGINX Root Directory Content

First, we will move all the files & folders located at default NGINX web root location /var/www/html to its new location, say, /mnt/website

$ sudo rsync -av /var/www/html /mnt/website

After this, you will find html folder at /mnt/website as /mnt/website/html

Bonus Read: How to Disable NGINX Cache

Update NGINX configuration

Open the file using a text editor

$ sudo vi /etc/nginx/sites-available/default

Update the line that starts with root and change its location to /mnt/website/html shown in bold

server { listen 80; listen [::]:80; root /mnt/website/html; index index.php index.html index.htm; server_name example.com www.example.com; location / { try_files $uri $uri/ /index.php?$args; }
......
......

If your site configuration is located in a different file (e.g /etc/nginx/sites-available/website) then update that file, instead. Also, if you have multiple configuration files at /etc/nginx/sites-available update them all, as described above.

Bonus Read : How to Redirect 404 to Home Page in NGINX

Restart NGINX web server

Check NGINX configuration

$ sudo nginx -t

If you don’t get any error message, restart NGINX server.

$ sudo service nginx reload #debian/ubuntu
$ systemctl restart nginx #redhat/centos

That’s it! Now NGINX will serve website requests from new location.

By the way, if you want to create charts & dashboards to monitor your business or website, you can try Ubiq. We offer a 14-day free trial.

mm

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.

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.

 { ; ;
} ~ { localhost:; }

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.

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/ ;
} { ;
}

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:

 { ; }

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.

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 127.0.0.1 and port 8080:

 { 127.0.0.1:; # Additional server configuration}
 { ; ; }
  1. Exact name
  2. Longest wildcard starting with an asterisk, such as *.example.org
  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.

 { ; }

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.

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 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.

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.

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.

Дополнительно:  Teclast X98 Air III

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.

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:

 { $host/'; $host/'; ;
}

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

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.


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.

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.

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:

Root inside Location Block¶

 
 

Multiple Index Directives¶

 
 

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.

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 www.example.com or
just the plain example.com — 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
https.

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.

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
example:

  • “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.

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
filesystem.

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:
 $ 

FastCGI Path in Script Filename¶

 
 

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.

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.

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.

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.

 

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
    headaches.
  • Use curl.

VirtualBox¶

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.:

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)

 

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
system.

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.

 

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:

 

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.

Incorrect context¶

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

 
 

Оцените статью
Master Hi-technology