What is the difference between Nginx variables $host, $http_host, and $server_name?

What is the difference between the three Nginx variables $host, $http_host, and $server_name?

I have a rewrite rule where I’m not sure which one I should be using:

I’m looking for an answer that doesn’t just say ‘use ___ variable in your rewrite rule’ but also explains the theoretical differences between them.

asked Jul 17, 2015 at 1:50

The difference is explained in the nginx documentation:

answered Jul 17, 2015 at 2:07

43 gold badges506 silver badges970 bronze badges

I would like to add another important point not mentioned in the accepted answer.

$host do NOT have port number, while $http_host does include the port number.

edit: not always.

I set up a header «add_header Y-blog-http_host «$http_host» always;»

Then curl -I -L domain.com:80 (or 443) and the header doesn’t show a port number at all. Verified with nginx-extra 1.10.3. Is is because it’s common http(s) ports or nginx configuration? This comment just to say things do not always behave the way you think.

answered Jan 4, 2018 at 1:37

I also struggled with this for a while. It became clear when I understood that $http_XXXXX refer to all declared header variables.

Read it from https://stackoverflow.com/questions/15414810/whats-the-difference-of-host-and-http-host-in-nginx

answered Jan 16, 2019 at 10:15

1 gold badge7 silver badges22 bronze badges

TL;DR: If you don’t use regular expressions in server_name you can ignore this answer 😉.

Since this aspect hasn’t been mentioned at all in other answers, but it’s something that I found somewhat annoying: I use $host in the creation of my log file names, like so:

Alas, if you use a regular expression in your server_name stanza like:

Your $host will actually end up containing the regular expression like so (yep, including the backslash and everything):

I for one found this very annoying and ended up changing my regular expression to:

to capture the full name for reuse in the log file name. The respective stanza was then changed to:

answered May 6, 2022 at 22:26

2 gold badges22 silver badges42 bronze badges

Привет! Сегодня мы поговорим о таком нужном понятии, как виртуальные хосты (Virtual Hosts) в web-сервере nginx. В качестве примера мы будем использовать операционную систему Ubuntu. Для других Linux-систем настройка будет выглядеть очень похоже. Эта статья-инструкция будет интересна, в основном, начинающим web-мастерам и администраторам, т.к. у них чаще всего возникает данный вопрос.

Многие команды в этой инструкции требуют наличия у вашего пользователя прав sudoer’а на VPS. Поэтому, если у вас их нет, настроить виртуальные хосты у вас, к сожалению, вряд ли получится.

Предустановка

Сейчас я скажу вещь, которую необходимо знать каждому! Для того, чтоб настроить виртуальный хост в nginx, вам нужен установленный на вашей машине wеb-сервер nginx. Капитан Очевидность с нами! Если nginx у вас уже установлен, можете смело пропускать этот шаг и двигаться дальше по инструкции. Если же его у вас по каким-то причинам на машине всё ещё нет, введите в консоли команду:

sudo apt-get install -y nginx

Читайте также:  Несколько виртуальных хостов nginx

Опцию «-y» команде apt-get мы добавляем для того, чтоб не отвечать да-да-да на назойливые вопросы установщика, ведь мы уверены, что хотим поставить этот пакет и согласны с использованием занимаемого им места на диске. Если вы всё-таки не уверены, что со всем согласны, то не добавляйте эту опцию.

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

Итак, прежде чем создавать виртуальный хост, давайте сделаем папку сайта, где разместим все файлики, с которыми будет работать наш web-сервер.

Путь к этой папке в конфигурации создаваемого хоста будет Document Root, своего рода контекстом, точкой изоляции, выше которой снаружи без предварительной настройки конфигурации подняться нельзя и относительно которой строятся пути до запрашиваемых файлов. С опцией «-p» у команды mkdir мы можем не заботиться о создании родительских директорий, они будут созданы автоматически:

sudo mkdir -p /var/www/mysite.ru/public_html

Здесь мы используем реальный подтверждённый DNS домен с корректными записями, указывающими на нашу машину. Для создания виртуального хоста с незарегистрированным доменом, например, для локальной разработки, вам необходимо внести соответствующую запись в файле /etc/hosts. Подробнее об этом будет в конце статьи.

Permissions

Now only the root user has rights to our created folder. We have to give permissions to the directory for the right user, so as not to work with it constantly in super-user mode. You can change the «www-data» user used below to something else, but by default, nginx runs as this user.

sudo chown -R www-data:www-data /var/www/mysite.ru/public_html

Now let’s make it so that all users can read our new files:

sudo chmod 755 /var/www

We mean that we work with a VPS where all users do nothing wrong or where only you are. Therefore, we can give 755 permissions to the /var/www folder. If in your case it is impossible to give all users of the system the right to read this directory, study the issue with the differentiation of rights and configure it yourself.

Now you’re all set with permissions!

Creating a page

Now we need to place in our folder some static files (HTML pages, pictures, scripts, styles, etc.) that our server will distribute. Let’s create the index.htm HTML page, which will be the main page on our site:

sudo nano /var/www/mysite.ru/public_html/index.htm

And add some markup to it, which will be shown to the user:

Save and exit.

Create virtual host configuration

We have come to the creation of a configuration file for our new virtual host, which will contain all the information about the site necessary for the web server.

In nginx, in the /etc/nginx/sites-available directory, there is a template for the created configurations. Let’s copy it for our website:

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/mysite.ru

Virtual host configuration

Open the new configuration file and you will see all the necessary information that you need to fill in.

sudo nano /etc/nginx/sites-available/mysite.ru

We need to make changes to the current configuration. The result for our simple case should be something like this:

That’s it, we’re done with this file. Save it and close it.

Virtual host activation

Nginx has the sites-available and sites-enabled folders. The first one stores the configurations of ALL virtual hosts that may be on this server, and the sites-enabled directory contains symbolic links to active ones. No one forbids placing the original configuration file in sites-enabled, and not a link, but this will be less convenient, because. if you need to disable it, you will either have to delete the file (then it will be problematic to turn it back on), or move it to another directory (then we must remember where we transferred it). Much easier to bang a symbolic link!

Читайте также:  Почему не работает сайт? - RU-CENTER

Therefore, now, in order to activate our virtual host, we need to create a symbolic link between the sites-available directory, where our configuration file is located, and sites-enabled. Apache has a special a2ensite command for this. There is no such command in nginx, so let’s run the following:

sudo ln -s /etc/nginx/sites-available/mysite.ru /etc/nginx/sites-enabled/mysite.ru

To avoid «conflicting server name error» and to be sure that your site gives the necessary information, you can remove the default one from the number of active hosts:

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

Reboot

We have already gone through a lot of steps and almost everything is set up. Let’s now reload our web server to apply the new configuration, but before that it’s good practice to make sure everything is correct with the configuration and that nginx understands it correctly. To do this, run nginx diagnostics with the following command:

sudo nginx -t

Such a check is extremely necessary when configuring on production servers, so that it does not happen that we called the nginx restart command, and it could not start due to an incorrect configuration, and all our virtual hosts do not respond.

If you received something like this in response:

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

Then everything is fine and you can safely restart the server with the command:

sudo service nginx restart

Otherwise, you need to look at the host configuration file. You didn’t state something right there.

Настройка локальных хостов

sudo nano /etc/hosts

Если вы работаете под Windows, то файл с локальных хостов должен лежать примерно по этому пути C:WindowsSystem32driversetchosts.

Добавляем запись о новом локальном хосте в файл. В нашем случае нужно добавить две записи, т.к. в server_name мы указали два домена.

12.34.56.789 mysite.ru
12.34.56.789 www.mysite.ru

Теперь до тех пор, пока эта запись не будет удалена, обращения по адресу mysite.ru будут получать информацию о данном хосте из этого файлика и перенаправлять вас к вашему удаленному серверу. Если сервер развернут локально, нужно написать вместо «12.34.56.789» «127.0.0.1».

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

Результаты

Теперь мы можем посмотреть результаты наших трудов! Вводим в браузере адрес http://mysite.ru или http://www.mysite.ru и любуемся созданной нами главной страницей из index.htm. Оба адреса должны показывать нашу главную страницу. Вот и всё! Наш виртуальный хост прекрасно работает.

Заключение

Tag:
The front end
nginx

The global variable

Nginx has some common global variables that can be used anywhere in the configuration. To name some of the more common ones:

How does Nginx set variables

Nginx configuration files use a tiny programming language. As a programming language, there is always such a thing as «variables», but in Nginx configuration, variables can only hold one type of value, which is a string.

Variable values can be dynamically specified using the set configuration directive, Nginx variable names are preceded by a $sign, and all Nginx variables must be prefixed with a $prefix when referenced in Nginx configuration files

set $limit_rate 1K; Limit the response transfer rate to the client.
Copy the code

Note also that if you want to print the $symbol itself, you can do this:

Nginx variable implementation principle

The corresponding modules of Nginx variables can be divided into: variable supply module and variable use module

The Map module provides more possibilities by mapping new variables

For example, request header Host: map.xu.org.cn generic domain name matching takes precedence over regular matching, so $name is 2.

Split_client module specifies variables for a small number of users (AB tests can be implemented)

The module compiles into Nginx by default and creates new variables based on existing variables (existing variables can be strings, one or more variables, and combinations of variables and strings).

Читайте также:  Глава 4. Системы хранения

Rules of the case

The GEO module generates new variables based on IP address ranges

Simple instructions consist of names and arguments separated by Spaces and terminated with a semicolon.

# Simple instructions
root /data/www;
Copy the code

Block-level instruction

In a configuration file, instructions that are not placed in any context are placed in the main context. Events and HTTP directives are placed on the main context, server is placed on HTTP, and Location is placed on server.

Grammar rules

The location directive is used to match only URIs, ignoring arguments, using either a valid string or a regular expression

After the instruction:

Priority

Location = location ^~ path location ~,~* regular order location partial start path location /

That is: Exact match longest string match, full match (but also to match re) Prefix match Regular match Normal match (longest string match, partial match) general match

Note

Directives have a Context, and different directives may have different contexts to apply.

Main Global configuration

Defined in the main section. In the case of high concurrency, the performance loss caused by register reconstruction due to multi-CPU core switching can be reduced by setting CPU stickiness. Worker_cpu_affinity 0001 0010 0100 1000; (Quad-core).

The HTTP configuration

Several virtual hosts are supported on HTTP services. Each virtual host corresponds to a server configuration item, which contains the configuration of the virtual host. When providing the proxy of mail service, several servers can also be established, and each server can be distinguished by listening for address or port.

Server_name extension

1. Server_name Using the first name as the primary domain name works with the server_name_in_redirect to redirect multiple subdomain names to the primary domain name.

Serve_name can create variables using regular expression parentheses () and Angle parentheses. to name variables.

3. Example.com can match example.com *. Example.com

4. _ Matches all domain names

Matching order of multiple server blocks

Nginx access control module will be installed by default, and simple writing, can be multiple allow/deny, allow or deny a certain IP address or IP segment access, meet any rule in turn stop matching.

We also use the httpd-devel tool htpasswd to set the login password for the access path :(I did not verify here)

This generates a password file that is encrypted with CRYPT by default. Open the two lines of comment above for nginx-status and restart nginx to take effect.

Lists the directory autoindex

Nginx does not allow listing entire directories by default. If you need this feature, open the nginx.conf file and add autoindex on to the location, server, or HTTP section; The other two parameters had better be added as well:

Nginx if judgment

expires 3m;
Copy the code

Spatial unit

client_max_body_size 10m;
Copy the code

Recommend a document

Front-end-basics is a technical document that starts from a front-end base and then extends to a full stack.

Document address: docs.chenfangxu.com/

You may like

$server_name is equals to server_name (in Nginx config), even if server_name is wildcard (Ex: server_name *.example.org;)

$http_host

$http_host always equals Host request header field

Host name from the request line

Most browser send the request like this

GET /test/ HTTP/1.1
Host: host.name

Most browser doesn’t send the request like this

GET http://host.name/test/ HTTP/1.1

Ref: ngx_http_core_module, Nginx $host validation

answered Oct 21, 2022 at 1:25

2 silver badges4 bronze badges

Оцените статью
Хостинги