How to see all virtual hosts in nginx
Nginx usually stores one virtual host per configuration file and each one is configured using the server_name entry. One could create a custom shell script to parse these files, but there is a more reliable method.
Using the configuration test option
Normally you could test the nginx configuration using the -t
option. The capitalized -T
does the same, but also shows the configuration. This can be great for showing any configured virtual host and the related hostname(s).
nginx -T -q | grep server_name
This will show the related entries in the configuration, but not as clean as we always want.
nginx -T -q | grep server_name | awk '{if($1=="server_name"){print}}' | tr ' ' '\n' | grep -v '^$' | tr -d ';' | grep -v server_name | sort -u
So what this does do?
- nginx: show the configuration
- grep: only filter out the configured server_name lines
- awk: only show lines where there is actual configuration of the server_name
- tr: replace spaces with line breaks
- grep: strip out empty lines
- tr: delete the semi-colon
- grep: strip out the server_name keyword
- sort: sort and make output unique
The output then only shows the configured domains:
archive.linux-audit.com
linux-audit.com
www.linux-audit.com
Perfect!