How do I find the path to pg_hba.conf from the shell?
I would like to obtain the path to pg_hba.conf from the shell. The path varies between versions of PostgreSQL. For instance, for 8.4 and 9.1:
I have tried the pg_config command, but it does not seem to include this information.
This is so that I can use a uniform command for opening pg_hba.conf and other PostgreSQL configuration files for editing.
8 Answers 8
pg_config is for compliation information, to help extensions and client programs compile and link against PostgreSQL. It knows nothing about the active PostgreSQL instance(s) on the machine, only the binaries.
pg_hba.conf can appear in many other places depending on how Pg was installed. The standard location is pg_hba.conf within the data_directory of the database (which could be in /home , /var/lib/pgsql , /var/lib/postgresql/[version]/ , /opt/postgres/ , etc etc etc) but users and packagers can put it wherever they like. Unfortunately.
The only valid ways find pg_hba.conf is to ask a running PostgreSQL instance where it’s pg_hba.conf is, or ask the sysadmin where it is. You can’t even rely on asking where the datadir is and parsing postgresql.conf because an init script might passed a param like -c hba_file=/some/other/path when starting Pg.
What you want to do is ask PostgreSQL:
This command must be run on a superuser session, so for shell scripting you might write something like:
and set the environment variables PGUSER , PGDATABASE , etc to ensure that the connection is right.
Yes, this is somewhat of a chicken-and-egg problem, in that if the user can’t connect (say, after screwing up editing pg_hba.conf ) you can’t find pg_hba.conf in order to fix it.
Another option is to look at the ps command’s output and see if the postmaster data directory argument -D is visible there, e.g.
since pg_hba.conf will be inside the data directory (unless you’re on Debian/Ubuntu or some derivative and using their packages).
If you’re targeting specifically Ubuntu systems with PostgreSQL installed from Debian/Ubuntu packages it gets a little easier. You don’t have to deal with hand-compiled-from-source Pg that someone’s initdb ‘d a datadir for in their home dir, or an EnterpriseDB Pg install in /opt, etc. You can ask pg_wrapper , the Debian/Ubuntu multi-version Pg manager, where PostgreSQL is using the pg_lsclusters command from pg_wrapper .
Pg hba conf где
Общий формат файла pg_hba.conf — набор записей, по одной на строку. Пустые строки игнорируются, как и любой текст комментария после знака # . Запись может быть продолжена на следующей строке, для этого нужно завершить строку обратной косой чертой. (Обратная косая черта является спецсимволом только в конце строки.) Запись состоит из нескольких полей, разделённых пробелами и/или табуляциями. Поля могут содержать пробелы, если содержимое этих полей заключено в кавычки. Если в кавычки берётся какое-либо ключевое слово в поле базы данных, пользователя или адресации (например, all или replication ), то слово теряет своё особое значение и просто обозначает базу данных, пользователя или сервер с данным именем. Обратная косая черта обозначает перенос строки даже в тексте в кавычках или комментариях.
Каждая запись обозначает тип соединения, диапазон IP-адресов клиента (если он соотносится с типом соединения), имя базы данных, имя пользователя, и способ аутентификации, который будет использован для соединения в соответствии с этими параметрами. Первая запись с соответствующим типом соединения, адресом клиента, указанной базой данных и именем пользователя применяется для аутентификации. Процедур « fall-through » или « backup » не предусмотрено: если выбрана запись и аутентификация не прошла, последующие записи не рассматриваются. Если же ни одна из записей не подошла, в доступе будет отказано.
Записи могут иметь следующие форматы:
Значения полей описаны ниже:
Управляет подключениями через Unix-сокеты. Без подобной записи подключения через Unix-сокеты невозможны. host
Управляет подключениями, устанавливаемыми по TCP/IP. Записи host соответствуют подключениям c SSL и без SSL , а также подключениям, защищённым механизмами GSSAPI и не защищённым GSSAPI .
Примечание
Удалённое соединение по TCP/IP невозможно, если сервер запущен без определения соответствующих значений для параметра конфигурации listen_addresses, поскольку по умолчанию система принимает подключения по TCP/IP только для локального адреса замыкания localhost .
Управляет подключениями, устанавливаемыми по TCP/IP с применением шифрования SSL .
Чтобы использовать эту возможность, сервер должен быть собран с поддержкой SSL . Более того, механизм SSL должен быть включён параметром конфигурации ssl (подробнее об этом в Разделе 19.9). В противном случае запись hostssl не играет роли (не считая предупреждения о том, что ей не будут соответствовать никакие подключения). hostnossl
Этот тип записей противоположен hostssl , ему соответствуют только подключения по TCP/IP без шифрования SSL . hostgssenc
Управляет подключениями, устанавливаемыми по TCP/IP, для которых применяется шифрование GSSAPI .
Этот тип записей противоположен hostgssenc ; ему соответствуют только подключения по TCP/IP без шифрования GSSAPI . база
Определяет, каким именам баз данных соответствует эта запись. Значение all определяет, что подходят все базы данных. Значение sameuser определяет, что данная запись соответствует, только если имя запрашиваемой базы данных совпадает с именем запрашиваемого пользователя. Значение samerole определяет, что запрашиваемый пользователь должен быть членом роли с таким же именем, как и у запрашиваемой базы данных. ( samegroup — это устаревший, но допустимый вариант значения samerole .) Суперпользователи, несмотря на то, что они имеют полные права, считаются включёнными в samerole , только когда они явно входят в такую роль, непосредственно или косвенно. Значение replication показывает, что запись соответствует, когда запрашивается подключение для физической репликации, но не когда запрашивается подключение для логической. Имейте в виду, что для подключений физической репликации не указывается какая-то конкретная база данных, в то время как для подключений логической репликации должна указываться конкретная база. Любое другое значение воспринимается как имя определённой базы PostgreSQL . Несколько имён баз данных можно указать, разделяя их запятыми. Также можно задать отдельный файл с именами баз данных, написав имя файла после знака @ . пользователь
Указывает, какому имени (или именам) пользователя базы данных соответствует эта запись. Значение all указывает, что запись соответствует всем пользователям. Любое другое значение задаёт либо имя конкретного пользователя базы данных, либо имя группы (если это значение начинается с + ). (Напомним, что в PostgreSQL нет никакой разницы между пользователем и группой; знак + означает « совпадение любых ролей, которые прямо или косвенно являются членами роли » , тогда как имя без знака + является подходящим только для этой конкретной роли.) В связи с этим, суперпользователь рассматривается как член роли, только если он явно является членом этой роли, прямо или косвенно, а не только потому, что он является суперпользователем. Несколько имён пользователей можно указать, разделяя их запятыми. Файл, содержащий имена пользователей, можно указать, поставив знак @ в начале его имени. адрес
Указывает адрес (или адреса) клиентской машины, которым соответствует данная запись. Это поле может содержать или имя компьютера, или диапазон IP-адресов, или одно из нижеупомянутых ключевых слов.
Типичные примеры диапазонов адресов IPv4, указанных таким образом: 172.20.143.89/32 для одного компьютера, 172.20.143.0/24 для небольшой и 10.6.0.0/16 для крупной сети. Диапазон адресов IPv6 может выглядеть как ::1/128 для одного компьютера (это адрес замыкания IPv6) или как fe80::7a31:c1ff:0000:0000/96 для небольшой сети. 0.0.0.0/0 представляет все адреса IPv4, а ::0/0 — все адреса IPv6. Чтобы указать один компьютер, используйте длину маски 32 для IPv4 или 128 для IPv6. Опускать замыкающие нули в сетевом адресе нельзя.
Запись, сделанная в формате IPv4, подойдёт только для подключений по IPv4, а запись в формате IPv6 подойдёт только для подключений по IPv6, даже если представленный адрес находится в диапазоне IPv4-в-IPv6. Имейте в виду, что записи в формате IPv6 не будут приниматься, если системная библиотека С не поддерживает адреса IPv6.
Вы также можете прописать значение all , чтобы указать любой IP-адрес, samehost , чтобы указать любые IP-адреса данного сервера, или samenet , чтобы указать любой адрес любой подсети, к которой сервер подключён напрямую.
Если определено имя компьютера (всё, что не является диапазоном IP-адресов или специальным ключевым словом, воспринимается как имя компьютера), то оно сравнивается с результатом обратного преобразования IP-адреса клиента (например, обратного DNS-запроса, если используется DNS). При сравнении имён компьютеров регистр не учитывается. Если имена совпали, выполняется прямое преобразование имени (например, прямой DNS-запрос) для проверки, относится ли клиентский IP-адрес к адресам, соответствующим имени. Если двусторонняя проверка пройдена, запись считается соответствующей компьютеру. (В качестве имени узла в файле pg_hba.conf должно указываться то, что возвращается при преобразовании IP-адреса клиента в имя, иначе строка не будет соответствовать узлу. Некоторые базы данных имён позволяют связать с одним IP-адресом несколько имён узлов, но операционная система при попытке разрешить IP-адрес возвращает только одно имя.)
Указание имени, начинающееся с точки ( . ), соответствует суффиксу актуального имени узла. Так, .example.com будет соответствовать foo.example.com (а не только example.com ).
Когда в pg_hba.conf указываются имена узлов, следует добиться, чтобы разрешение имён выполнялось достаточно быстро. Для этого может быть полезен локальный кеш разрешения имён, например, nscd . Вы также можете включить конфигурационный параметр log_hostname , чтобы видеть в журналах имя компьютера клиента вместо IP-адреса.
Эти поля не применимы к записям local .
Примечание
Пользователи часто задаются вопросом, почему имена серверов обрабатываются таким сложным, на первый взгляд, способом, с разрешением двух имён, включая обратный запрос клиентского IP-адреса. Это усложняет процесс в случае, если обратная DNS-запись клиента не установлена или включает в себя нежелательное имя узла. Такой способ избран, в первую очередь, для повышения эффективности: в этом случае соединение требует максимум два запроса разрешения, один прямой и один обратный. Если есть проблема разрешения с каким-то адресом, то она остаётся проблемой этого клиента. Гипотетически, могла бы быть реализована возможность во время каждой попытки соединения выполнять только прямой запрос для разрешения каждого имени сервера, упомянутого в pg_hba.conf . Но если список имён велик, процесс был бы довольно медленным, а в случае наличия проблемы разрешения у одного имени сервера, это стало бы общей проблемой.
Также обратный запрос необходим для того, чтобы реализовать возможность соответствия суффиксов, поскольку для сопоставления с шаблоном требуется знать фактическое имя компьютера клиента.
Обратите внимание, что такое поведение согласуется с другими популярными реализациями контроля доступа на основе имён, такими как Apache HTTP Server и TCP Wrappers.
Эти два поля могут быть использованы как альтернатива записи IP-адрес / длина-маски . Вместо того, чтобы указывать длину маски, в отдельном столбце указывается сама маска. Например, 255.0.0.0 представляет собой маску CIDR для IPv4 длиной 8 бит, а 255.255.255.255 представляет маску CIDR длиной 32 бита.
Эти поля не применимы к записям local . метод-аутентификации
Указывает метод аутентификации, когда подключение соответствует этой записи. Варианты выбора приводятся ниже; подробности в Разделе 21.3. Все значения воспринимаются с учётом регистра и должны быть записаны в нижнем регистре, даже аббревиатуры типа ldap .
Разрешает безусловное подключение. Этот метод позволяет тому, кто может подключиться к серверу с базой данных PostgreSQL , войти под любым желаемым пользователем PostgreSQL без введения пароля и без какой-либо другой аутентификации. За подробностями обратитесь к Разделу 21.4. reject
Отклоняет подключение безусловно. Эта возможность полезна для « фильтрации » некоторых серверов группы, например, строка reject может отклонить попытку подключения одного компьютера, при этом следующая строка позволяет подключиться остальным компьютерам в той же сети. scram-sha-256
Проверяет пароль пользователя, производя аутентификацию SCRAM-SHA-256. За подробностями обратитесь к Разделу 21.5. md5
Проверяет пароль пользователя, производя аутентификацию SCRAM-SHA-256 или MD5. За подробностями обратитесь к Разделу 21.5. password
Требует для аутентификации введения клиентом незашифрованного пароля. Поскольку пароль посылается простым текстом через сеть, такой способ не стоит использовать, если сеть не вызывает доверия. За подробностями обратитесь к Разделу 21.5. gss
Для аутентификации пользователя использует GSSAPI. Этот способ доступен только для подключений по TCP/IP. За подробностями обратитесь к Разделу 21.6. Он может применяться в сочетании с шифрованием GSSAPI. sspi
Для аутентификации пользователя использует SSPI. Способ доступен только для Windows. За подробностями обратитесь к Разделу 21.7. ident
Получает имя пользователя операционной системы клиента, связываясь с сервером Ident, и проверяет, соответствует ли оно имени пользователя базы данных. Аутентификация ident может использоваться только для подключений по TCP/IP. Для локальных подключений применяется аутентификация peer. За подробностями обратитесь к Разделу 21.8. peer
Получает имя пользователя операционной системы клиента из операционной системы и проверяет, соответствует ли оно имени пользователя запрашиваемой базы данных. Доступно только для локальных подключений. За подробностями обратитесь к Разделу 21.9. ldap
Проводит аутентификацию, используя сервер LDAP . За подробностями обратитесь к Разделу 21.10. radius
Проводит аутентификацию, используя сервер RADIUS. За подробностями обратитесь к Разделу 21.11 cert
Проводит аутентификацию, используя клиентский сертификат SSL. За подробностями обратитесь к Разделу 21.12 pam
Проводит аутентификацию, используя службу подключаемых модулей аутентификации (PAM), предоставляемую операционной системой. За подробностями обратитесь к Разделу 21.13. bsd
Проводит аутентификацию, используя службу аутентификации BSD, предоставляемую операционной системой. За подробностями обратитесь к Разделу 21.14.
После поля метод-аутентификации может идти поле (поля) вида имя = значение , определяющее параметры метода аутентификации. Подробнее о параметрах, доступных для различных методов аутентификации, рассказывается ниже.
Помимо описанных далее параметров, относящихся к различным методам, есть один общий параметр аутентификации clientcert , который можно задать в любой записи hostssl . Он может принимать значения verify-ca и verify-full . В обоих случаях клиент должен предоставить годный (доверенный) сертификат SSL, но вариант verify-full дополнительно требует, чтобы значение cn (Common Name, Общее имя) в сертификате совпадало с именем пользователя или применимым сопоставлением. Это указание работает подобно методу аутентификации cert (см. Раздел 21.12), но позволяет связать проверку клиентских сертификатов с любым методом аутентификации, поддерживающим записи hostssl .
В любой записи, включающей аутентификацию по клиентскому сертификату (то есть в записи с методом аутентификации cert или с параметром clientcert ), в дополнительном параметре clientname можно выбрать сопоставляемый при проверке элемент учётных данных в клиентском сертификате. Этот параметр может иметь одно из двух значений. Если указано значение clientname=CN (оно подразумевается по умолчанию), имя пользователя сопоставляется с полем Common Name (CN) . Если указано значение clientname=DN — с полем Distinguished name (DN) . Этот вариант, вероятно, будет лучше использовать с сопоставлениями имён пользователей. Сравнение DN выполняется в формате RFC 2253. Извлечь поле DN в этом формате из клиентского сертификата можно так:
Использовать данный вариант следует с осторожностью, особенно когда для сопоставлений DN применяются регулярные выражения.
Pg hba conf где
Client authentication is controlled by a configuration file, which traditionally is named pg_hba.conf and is stored in the database cluster’s data directory. (HBA stands for host-based authentication.) A default pg_hba.conf file is installed when the data directory is initialized by initdb . It is possible to place the authentication configuration file elsewhere, however; see the hba_file configuration parameter.
The general format of the pg_hba.conf file is a set of records, one per line. Blank lines are ignored, as is any text after the # comment character. A record can be continued onto the next line by ending the line with a backslash. (Backslashes are not special except at the end of a line.) A record is made up of a number of fields which are separated by spaces and/or tabs. Fields can contain white space if the field value is double-quoted. Quoting one of the keywords in a database, user, or address field (e.g., all or replication ) makes the word lose its special meaning, and just match a database, user, or host with that name. Backslash line continuation applies even within quoted text or comments.
Each record specifies a connection type, a client IP address range (if relevant for the connection type), a database name, a user name, and the authentication method to be used for connections matching these parameters. The first record with a matching connection type, client address, requested database, and user name is used to perform authentication. There is no “ fall-through ” or “ backup ” : if one record is chosen and the authentication fails, subsequent records are not considered. If no record matches, access is denied.
A record can have several formats:
The meaning of the fields is as follows:
This record matches connection attempts using Unix-domain sockets. Without a record of this type, Unix-domain socket connections are disallowed.
Remote TCP/IP connections will not be possible unless the server is started with an appropriate value for the listen_addresses configuration parameter, since the default behavior is to listen for TCP/IP connections only on the local loopback address localhost .
This record matches connection attempts made using TCP/IP, but only when the connection is made with SSL encryption.
To make use of this option the server must be built with SSL support. Furthermore, SSL must be enabled by setting the ssl configuration parameter (see Section 19.9 for more information). Otherwise, the hostssl record is ignored except for logging a warning that it cannot match any connections.
This record type has the opposite behavior of hostssl ; it only matches connection attempts made over TCP/IP that do not use SSL .
This record matches connection attempts made using TCP/IP, but only when the connection is made with GSSAPI encryption.
This record type has the opposite behavior of hostgssenc ; it only matches connection attempts made over TCP/IP that do not use GSSAPI encryption.
Specifies which database name(s) this record matches. The value all specifies that it matches all databases. The value sameuser specifies that the record matches if the requested database has the same name as the requested user. The value samerole specifies that the requested user must be a member of the role with the same name as the requested database. ( samegroup is an obsolete but still accepted spelling of samerole .) Superusers are not considered to be members of a role for the purposes of samerole unless they are explicitly members of the role, directly or indirectly, and not just by virtue of being a superuser. The value replication specifies that the record matches if a physical replication connection is requested, however, it doesn’t match with logical replication connections. Note that physical replication connections do not specify any particular database whereas logical replication connections do specify it. Otherwise, this is the name of a specific PostgreSQL database. Multiple database names can be supplied by separating them with commas. A separate file containing database names can be specified by preceding the file name with @ .
Specifies which database user name(s) this record matches. The value all specifies that it matches all users. Otherwise, this is either the name of a specific database user, or a group name preceded by + . (Recall that there is no real distinction between users and groups in PostgreSQL ; a + mark really means “ match any of the roles that are directly or indirectly members of this role ” , while a name without a + mark matches only that specific role.) For this purpose, a superuser is only considered to be a member of a role if they are explicitly a member of the role, directly or indirectly, and not just by virtue of being a superuser. Multiple user names can be supplied by separating them with commas. A separate file containing user names can be specified by preceding the file name with @ .
Specifies the client machine address(es) that this record matches. This field can contain either a host name, an IP address range, or one of the special key words mentioned below.
Typical examples of an IPv4 address range specified this way are 172.20.143.89/32 for a single host, or 172.20.143.0/24 for a small network, or 10.6.0.0/16 for a larger one. An IPv6 address range might look like ::1/128 for a single host (in this case the IPv6 loopback address) or fe80::7a31:c1ff:0000:0000/96 for a small network. 0.0.0.0/0 represents all IPv4 addresses, and ::0/0 represents all IPv6 addresses. To specify a single host, use a mask length of 32 for IPv4 or 128 for IPv6. In a network address, do not omit trailing zeroes.
An entry given in IPv4 format will match only IPv4 connections, and an entry given in IPv6 format will match only IPv6 connections, even if the represented address is in the IPv4-in-IPv6 range. Note that entries in IPv6 format will be rejected if the system’s C library does not have support for IPv6 addresses.
You can also write all to match any IP address, samehost to match any of the server’s own IP addresses, or samenet to match any address in any subnet that the server is directly connected to.
If a host name is specified (anything that is not an IP address range or a special key word is treated as a host name), that name is compared with the result of a reverse name resolution of the client’s IP address (e.g., reverse DNS lookup, if DNS is used). Host name comparisons are case insensitive. If there is a match, then a forward name resolution (e.g., forward DNS lookup) is performed on the host name to check whether any of the addresses it resolves to are equal to the client’s IP address. If both directions match, then the entry is considered to match. (The host name that is used in pg_hba.conf should be the one that address-to-name resolution of the client’s IP address returns, otherwise the line won’t be matched. Some host name databases allow associating an IP address with multiple host names, but the operating system will only return one host name when asked to resolve an IP address.)
A host name specification that starts with a dot ( . ) matches a suffix of the actual host name. So .example.com would match foo.example.com (but not just example.com ).
When host names are specified in pg_hba.conf , you should make sure that name resolution is reasonably fast. It can be of advantage to set up a local name resolution cache such as nscd . Also, you may wish to enable the configuration parameter log_hostname to see the client’s host name instead of the IP address in the log.
These fields do not apply to local records.
Users sometimes wonder why host names are handled in this seemingly complicated way, with two name resolutions including a reverse lookup of the client’s IP address. This complicates use of the feature in case the client’s reverse DNS entry is not set up or yields some undesirable host name. It is done primarily for efficiency: this way, a connection attempt requires at most two resolver lookups, one reverse and one forward. If there is a resolver problem with some address, it becomes only that client’s problem. A hypothetical alternative implementation that only did forward lookups would have to resolve every host name mentioned in pg_hba.conf during every connection attempt. That could be quite slow if many names are listed. And if there is a resolver problem with one of the host names, it becomes everyone’s problem.
Also, a reverse lookup is necessary to implement the suffix matching feature, because the actual client host name needs to be known in order to match it against the pattern.
Note that this behavior is consistent with other popular implementations of host name-based access control, such as the Apache HTTP Server and TCP Wrappers.
These two fields can be used as an alternative to the IP-address / mask-length notation. Instead of specifying the mask length, the actual mask is specified in a separate column. For example, 255.0.0.0 represents an IPv4 CIDR mask length of 8, and 255.255.255.255 represents a CIDR mask length of 32.
These fields do not apply to local records.
Specifies the authentication method to use when a connection matches this record. The possible choices are summarized here; details are in Section 21.3. All the options are lower case and treated case sensitively, so even acronyms like ldap must be specified as lower case.
Allow the connection unconditionally. This method allows anyone that can connect to the PostgreSQL database server to login as any PostgreSQL user they wish, without the need for a password or any other authentication. See Section 21.4 for details.
Reject the connection unconditionally. This is useful for “ filtering out ” certain hosts from a group, for example a reject line could block a specific host from connecting, while a later line allows the remaining hosts in a specific network to connect.
Perform SCRAM-SHA-256 authentication to verify the user’s password. See Section 21.5 for details.
Perform SCRAM-SHA-256 or MD5 authentication to verify the user’s password. See Section 21.5 for details.
Require the client to supply an unencrypted password for authentication. Since the password is sent in clear text over the network, this should not be used on untrusted networks. See Section 21.5 for details.
Use GSSAPI to authenticate the user. This is only available for TCP/IP connections. See Section 21.6 for details. It can be used in conjunction with GSSAPI encryption.
Use SSPI to authenticate the user. This is only available on Windows. See Section 21.7 for details.
Obtain the operating system user name of the client by contacting the ident server on the client and check if it matches the requested database user name. Ident authentication can only be used on TCP/IP connections. When specified for local connections, peer authentication will be used instead. See Section 21.8 for details.
Obtain the client’s operating system user name from the operating system and check if it matches the requested database user name. This is only available for local connections. See Section 21.9 for details.
Authenticate using an LDAP server. See Section 21.10 for details.
Authenticate using a RADIUS server. See Section 21.11 for details.
Authenticate using SSL client certificates. See Section 21.12 for details.
Authenticate using the Pluggable Authentication Modules (PAM) service provided by the operating system. See Section 21.13 for details.
Authenticate using the BSD Authentication service provided by the operating system. See Section 21.14 for details.
After the auth-method field, there can be field(s) of the form name = value that specify options for the authentication method. Details about which options are available for which authentication methods appear below.
In addition to the method-specific options listed below, there is a method-independent authentication option clientcert , which can be specified in any hostssl record. This option can be set to verify-ca or verify-full . Both options require the client to present a valid (trusted) SSL certificate, while verify-full additionally enforces that the cn (Common Name) in the certificate matches the username or an applicable mapping. This behavior is similar to the cert authentication method (see Section 21.12) but enables pairing the verification of client certificates with any authentication method that supports hostssl entries.
On any record using client certificate authentication (i.e. one using the cert authentication method or one using the clientcert option), you can specify which part of the client certificate credentials to match using the clientname option. This option can have one of two values. If you specify clientname=CN , which is the default, the username is matched against the certificate’s Common Name (CN) . If instead you specify clientname=DN the username is matched against the entire Distinguished Name (DN) of the certificate. This option is probably best used in conjunction with a username map. The comparison is done with the DN in RFC 2253 format. To see the DN of a client certificate in this format, do
Care needs to be taken when using this option, especially when using regular expression matching against the DN .
Files included by @ constructs are read as lists of names, which can be separated by either whitespace or commas. Comments are introduced by # , just as in pg_hba.conf , and nested @ constructs are allowed. Unless the file name following @ is an absolute path, it is taken to be relative to the directory containing the referencing file.
Since the pg_hba.conf records are examined sequentially for each connection attempt, the order of the records is significant. Typically, earlier records will have tight connection match parameters and weaker authentication methods, while later records will have looser match parameters and stronger authentication methods. For example, one might wish to use trust authentication for local TCP/IP connections but require a password for remote TCP/IP connections. In this case a record specifying trust authentication for connections from 127.0.0.1 would appear before a record specifying password authentication for a wider range of allowed client IP addresses.
The pg_hba.conf file is read on start-up and when the main server process receives a SIGHUP signal. If you edit the file on an active system, you will need to signal the postmaster (using pg_ctl reload , calling the SQL function pg_reload_conf() , or using kill -HUP ) to make it re-read the file.
The preceding statement is not true on Microsoft Windows: there, any changes in the pg_hba.conf file are immediately applied by subsequent new connections.
The system view pg_hba_file_rules can be helpful for pre-testing changes to the pg_hba.conf file, or for diagnosing problems if loading of the file did not have the desired effects. Rows in the view with non-null error fields indicate problems in the corresponding lines of the file.
To connect to a particular database, a user must not only pass the pg_hba.conf checks, but must have the CONNECT privilege for the database. If you wish to restrict which users can connect to which databases, it’s usually easier to control this by granting/revoking CONNECT privilege than to put the rules in pg_hba.conf entries.
Some examples of pg_hba.conf entries are shown in Example 21.1. See the next section for details on the different authentication methods.
Example 21.1. Example pg_hba.conf Entries
| Prev | Up | Next |
| Chapter 21. Client Authentication | Home | 21.2. User Name Maps |
Submit correction
If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.
Where does PostgreSQL store configuration/conf files?
I have recently installed PostgreSQL on Ubuntu with the EnterpriseDB package. I can connect to the database locally, but I can’t configure it because I can’t find config files. I searched through entire hard drive and found only samples like pg_hba.conf.sample
Where are the PostgreSQL .conf files?
29 Answers 29
Or ask your database:
or, if logged in as the ubuntu user:
Ubuntu 13.04 installed using software centre :
The location for mine is:
Where are my postgres *.conf files?
Query the database with the sql query:
The reason you may have trouble finding postgresql.conf is because it is owned by postgres, not root.
Here is where mine is on Fedora 17:
Notice it is owned by postgres:
It has permission 600 which explains why you have a hard time finding it with a file search. The location of postgresql.conf will be different depending on what operating system you are using.
Here is the contents of mine:
To get the location of the pg_hba.conf file, you can also query the database like
You should get something like
If you have just installed it, it is possible that locate doesn’t help. In that case, the service should be running and you can run
to see where the postgresql-master is loading the config files from.
On Mac (Postgres installed using brew) :
![]()
Print pg_hba.conf file location:
Print postgresql.conf file location:
![]()
![]()
You can find other conf files by the following command:
Note: See usage using man:
For CentOS 6 and 7 and postgresql 9.2 (and below, I suppose, possibly Fedora and Redhat as well):
For CentOS 6 and 7 postgresql 9.3 or 9.4 (and above, I suppose):
For Ubuntu 14 and postgresql 9.3:
![]()
The answer may be that you have not initialized the database yet. After installing postgres, but before initializing the database, the postgres*.sql files will be absent. After initializing the database the postgres*.sql files will appear. (Centos 6, Postgres 9.3 demonstrated here)
30-07-2019
In Windows 10 pro:
![]()
As I don’t have access to postgres account (so can’t run SHOW config_file ) and my postgres is installed on Windows, none of the answers helped me, so I’m sharing my file location for future Windows readers:
In most cases: under $PGDATA , which is normally /var/lib/postgresql/data or something similar (at least it’s the default path if you use Docker images).
I like this thread because it documents the default locations for various postgresql.conf files on various architectures.
However, I’ve also gotten in trouble by relying on those defaults on installations where they have specified alternate locations. One way to find out where a particular config file is by querying the database directly: