How to Find Apache Document Root in Linux


The DocumentRoot is the top-level directory in the document tree visible from the web and this directive sets the directory in the configuration from which Apache2 or HTTPD looks for and serves web files from the requested URL to the document root.

DocumentRoot "/var/www/html"

then access to refers to /var/www/html/index.html. The DocumentRoot should be described without a trailing slash.

In this short quick tip, we will show you how to find the Apache DocumentRoot directory in a Linux system.

  1. Finding Apache Document Root
  2. Use the Super Global Variable
  3. – Coding Example for Getting PHP Root Directory With $_SERVER
  4. Execute the Dirname() Function
  5. – Discussing the Levels Parameter in PHP Version 7 and Above
  6. – Coding Example for Getting PHP Root Directory by Using Dirname()
  7. Use Dirname() With __DIR__
  8. – Coding Example for Getting PHP Root Path By Using __DIR__
  9. How To Get To Root Directory in PHP
  10. – Coding Example for Using the Chroot() Function
  11. PHP Get Root Directory of Website
  12. – Coding Example for Getting Root Directory of Website
  13. Comparing the Magical Constants
  14. – Coding Example for Comparing the Magical Constants
  15. Что за корневая папка?
  16. Содержимое папки root
  17. Где находится корень сайта?
  18. Для чего нужен корневой каталог?
  19. Как зайти в корень сайта
  20. Через терминал
  21. Через FTP-клиент
  22. Через панель управления хостинга
  23. Через стороннюю панель управления
  24. Через файловый менеджер
  25. Как загружать файлы в корневой каталог?
  26. Корень (слэш) в HTML и PHP
  27. PHP — Корень сайта
  28. Replies
  29. Site Content
  30. Server Configuration
  31. Reply
  32. Ubuntu/Debian
  33. CentOS/RHEL/Fedora
  34. Final thoughts
  35. Structure Of A Root Directory
  36. How Do I Find Root Directory Of A Website? Where Is Root Directory Of My Website?
  37. Method 1. cPanel
  38. Method 2. VPS Hosting
  39. How To Find System Root Directory In Windows?
  40. Final Thoughts
  41. 1. How to hide Apache Version and OS Identity from Errors
  42. 2. Disable Directory Listing
  43. 3. Keep updating Apache Regularly
  44. 4. Disable Unnecessary Modules
  45. 5. Run Apache as separate User and Group
  46. 6. Use Allow and Deny to Restrict access to Directories
  47. 7. Use mod_security and mod_evasive Modules to Secure Apache
  48. Mod_security
  49. 8. Disable Apache’s following of Symbolic Links
  50. 9. Turn off Server Side Includes and CGI Execution
  51. 10. Limit Request Size
  52. 11. Protect DDOS attacks and Hardening
  53. 12. Enable Apache Logging
  54. 13. Securing Apache with SSL Certificates
  55. Before You Begin
  56. Install NGINX
  57. Stable Versus Mainline
  58. Binary Versus Compiling from Source
  59. Installation Instructions
  60. Configuration Notes
  61. NGINX Configuration Best Practices
  62. Use Multiple Worker Processes
  63. Disable Server Tokens
  64. Set Your Site’s Root Directory
  65. Serve Content Over IPv4 and IPv6
  66. Static Content Compression
  67. Configuration Recap
  68. (Slightly More) Advanced Configurations

Finding Apache Document Root

$ grep -i 'DocumentRoot' /etc/apache2/sites-available/000-default.conf
$ grep -i 'DocumentRoot' /etc/apache2/sites-available/default-ssl.conf
Find Apache DocumentRoot in Ubuntu
Find Apache DocumentRoot in Ubuntu
$ grep -i 'DocumentRoot' /etc/httpd/conf/httpd.conf
$ grep -i 'DocumentRoot' /etc/httpd/conf.d/ssl.conf
Find Apache DocumentRoot in CentOS
Find Apache DocumentRoot in CentOS

Note that the location of the DocumentRoot directory may vary depending on the value of the DocumentRoot directive set in the Apache or httpd configuration.

If you want to change the location of the Apache DocumentRoot directory, please read our article that explains How to Change Default Apache ‘DocumentRoot’ Directory in Linux.

On a side note, the individual directories for all your virtual hosts must be located under the DocumentRoot. For example, if your DocumentRoot is /var/www/html, and you have two sites called and, you can create their directories as shown.

$ sudo mkdir -p /var/www/html/
$ sudo mkdir -p /var/www/html/

Then in the virtual host configuration files, point their DocumentRoot to the above directories.

Here are some additional guides about Apache web server, that you will find useful:

Php get root directoryThe PHP root directory can be extracted through PHP built-in functions and constants. Moreover, the stated directory can be changed to your preferred path. So, our expertly written article will educate you about the various simple ways to access your root directory along with changing it.

Continue reading to get the PHP root path printed on your browser window in a few seconds.

  • Get Root Directory: Use the Super Global Variable
  • Get Base Directory: Execute the Dirname() Function
  • PHP Root Path: Use Dirname() With __DIR__
  • How To Get To Root Directory in PHP: Use Chroot()
  • PHP Get Root Directory of Website: Going to the Top
  • PHP Root Directory Path: Comparing the Magical Constants
  • Winding Up

Use the Super Global Variable

You might find it hard to believe but the super global variable can help you in finding the PHP root directory path. Certainly, the PHP root path is stored on the of the $_SERVER array. Therefore, accessing the given element will return the parent directory path accurately. Also, it would be best to note that the $DOCUMENT_ROOT element is defined in the server’s configuration file.

– Coding Example for Getting PHP Root Directory With $_SERVER

Please feel free to see how the $_SERVER array helps in your root directory search process:

Execute the Dirname() Function

Certainly, you don’t need to worry if your currently installed version of PHP is below 5.3.0 because you can execute the . The dirname() function will let you pass the required file or folder path and an optional number of levels. Next, the same function will return the PHP root directory path with maximum accuracy.

Furthermore, its syntax is right here: dirname(path, levels).

– Discussing the Levels Parameter in PHP Version 7 and Above

In PHP version 7 and above, the dirname() function allows you to specify the number of levels while acquiring the PHP root directory. You can pass an integer value that comes above one as the second argument to the dirname() function. For example, if you want to PHP get base directory that is one level above your current directory, then you’ll pass two and so on.

– Coding Example for Getting PHP Root Directory by Using Dirname()

Imagine having a script file saved in the “src” directory that exists in the “MyWebsite” directory with the path: “C:xampphtdocsMyWebsitesrc.” Now, let’s assume you also want to get the base directory that exists three levels above your script file. Here, the simplest way to pass the path of your current file to the dirname() function is by passing the __FILE__ constant to it. Next, you’ll pass three as the number of levels.

Please have a look at this code representation that depicts the stated example in the easiest possible manner so you can use it in your programming practice:

Use Dirname() With __DIR__

Are you using a PHP version 5.3.0 and above, and looking for a solution to get the PHP root path? Then do nothing else except for passing the magical constant “__DIR__” to the . The given constant will return the path of your current directory and the dirname() function will return the PHP root directory of the same.

– Coding Example for Getting PHP Root Path By Using __DIR__

For instance, let’s discuss a case in which the main directory of your PHP project is “MyProject” and it is saved in the “htdocs” folder located in the xampp folder in C drive. This hypothetical directory consists of two subfolders: “assets” and “images” and your current file “myFile.php” is located in the “assets” folder.

Now, you may want to PHP get base directory path of your current directory. Here, you’ll simply pass the magic constant __DIR__ to the dirname() function to acquire accurate results.

Please feel free to use the short code snippet we have provided for you below that implements the dirname() function with the __DIR__ constant:

How To Get To Root Directory in PHP

Undeniably, the given function accepts a directory that apparently changes the PHP root directory of the current process to the same, and makes “/” the current directory.

You will need to use this syntax in any relevant code you are planning to create: chroot(directory).

– Coding Example for Using the Chroot() Function

Here is a code fragment to help you in switching to the root directory easily:

The chroot() function doesn’t work on Windows Operating System while it requires root privileges on the systems stated above.

PHP Get Root Directory of Website

Do you have a large website directory consisting of various directories, subdirectories, and files? Would you like to see the topmost level of your website directory without jumping through all the layers? Well, you can do this by applying a small trick with the combination of the and the $_SERVER variable. In the end, you’ll PHP get root directory of website without wasting your time in counting the levels backward.

– Coding Example for Getting Root Directory of Website

Comparing the Magical Constants

Interestingly, the __DIR__ and __FILE__ constants provide almost similar results. The only exception between both of them is that the __DIR__ constant returns the path of your current directory. On the other hand, the __FILE__ constant gives back the path of your current file. Therefore, you will notice a difference of one level when you use them inside the dirname() function.

– Coding Example for Comparing the Magical Constants

Let’s assume that you are willing to find the results returned by the two magical constants and their effect with the dirname function

Undoubtedly, being familiar with your PHP root directory path can be quite helpful while working on large projects. Having covered different ways to get the base directory path, here are some notable facts to help you ensure the correctness of your concepts:

  • The $_SERVER[“DOCUMENT_ROOT”] returns the PHP root directory of your current file
  • In PHP versions before 5.3, you can use the dirname() function with the __FILE__ constant and a level >= two to PHP get base directory of your current file
  • In PHP version from 5.3 and over, you can use the dirname() function with the __DIR__ constant to PHP get base directory of your current directory
  • You can get to the root directory by using the chroot() function in BSD and GNU Operating Systems
  • The combo of the explode() function with $_SERVER[“DOCUMENT_ROOT”] serves to be an efficient way to get the root directory

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Выясняем, что такое корневая директория, где находится корень сайта, и для чего она может понадобиться.

Что за корневая папка?

Корневая папка (корневой каталог, корень, root) — это ключевая директория компьютера или сервера. В частности, на базе Linux. С нее начинается файловая система, в ней хранятся все остальные подкаталоги, содержащие системные и пользовательские файлы.

Что касается сервера, это может быть точно такая же папка root, как и в любом дистрибутиве Linux, если мы говорим о выделенном сервере (физическом или виртуальном). Она будет содержать в себе те же компоненты, что и обычный компьютер. А в случае с виртуальным хостингом эта папка может называться public_html или www. Там будут только данные сайта. Получить доступ к «настоящему» root там не получится.

Тем не менее эта директория тоже будет считаться корнем сайта, и этот термин будет уместно использовать в отношении условных public_html или www. И в различных инструкциях авторы будут ссылаться именно на нее, упоминая root.

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Содержимое папки root

Как я уже сказал ранее, корневой каталог может представлять собой разные сущности в зависимости от типа сервера.

Например, на стандартной VDS/VPS такая директория может содержать в себе следующие папки:

  • /bin с системными программами, файлами и компонентами, необходимыми для загрузки ОС;
  • /boot с компонентами загрузчика, включающими в себя ядро Linux и базовый набор файлов для старта сервера;
  • /dev с файлами, привязанными к конкретным устройствам, подключаемым к системе;
  • /etc с другими скриптами и файлами, от которых не зависит запуск сервера.
Дополнительно:  An A-Z List of Common Latin Words Used in the English Language

Таких подкаталогов в корне может быть больше. Все зависит от конфигурации компьютера и ОС.

На виртуальном хостинге же папка public_html или ее аналог не содержит ничего, она пустая по умолчанию. В нее помещают HTML-документы, JS-скрипты и CSS-файлы необходимые для работы размещаемого сайта. Скорее всего, корнем для вас станет директория, в которую будет помещен файл index.html с главной страницей вашего ресурса.

Где находится корень сайта?

Зависит от того, что подразумевается под местоположением директории. Ведь мы уже выяснили, что корнем может быть папка www. Для html корнем станет именно директория, указанная в настройках сервера. А в случае с PHP, к примеру, это будет именно корневой каталог системы. В CMS WordPress — это хранилище в интерфейсе самой платформы, в Bitrix для поиска корня есть команда GetCurPage().

Для чего нужен корневой каталог?

Это основа вашего сервера и сайта. В нем лежат все ключевые компоненты. Он нужен для работы ресурса в целом. Удалите что-то из корня и распрощаетесь с рабочей операционной системой.

Если же говорить о конкретном применении root-каталога вебмастерами на практике, то речь пойдет о:

  • Загрузке файла Robots.txt, куда будут прописываться страницы, запрещенные для индексации поисковыми машинами. Через нее скрывают разного рода техническую информацию и конфиденциальные данные.
  • Добавлении документа sitemap.xml (карта сайта), где расписывается структура страниц, чтобы поисковому боту было проще ориентироваться на сайте.
  • Хранении данных, необходимых для подтверждения прав на владение ресурсом. Туда добавляют скрипты с настройками сторонних ресурсов для интеграции с ними (например, скрипт Яндекс.Метрики).
  • Хранении архива с резервной копией данных сайта. Бэкап необходим для восстановления проекта после сбоя и потери файлов.
  • Для установки CMS (соответствующие установочные скрипты запускаются именно из root-каталога).

Как зайти в корень сайта

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

Основной — через терминал. То есть при помощи командной строки и текстовых утилит. Но есть и специализированное программное обеспечение с графическим интерфейсом.

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

Через терминал

Чтобы управлять сервером через терминал, надо подключиться к нему через Secure Shell (SSH). Для этого:

  • Запускаем терминал (в macOS или Linux).
  • Вводим команду ssh root@IP-адрес сайта.
  • Указываем пароль администратора для авторизации.

Если вы управляете сервером через протокол SSH, то проще всего будет зайти в корневой каталог, используя встроенную в Linux команду для перемещения по жесткому диску. Речь идет о команде cd. Когда вы используете ее без дополнительных опций (не указывая конкретный путь), то она автоматически отправляет пользователя в корневую директорию сервера.

Сразу же можно проверить его содержимое, воспользовавшись командой ls.

Через FTP-клиент

Рассмотрим эту процедуру на примере утилиты FileZilla:

  1. Заходим на официальный сайт разработчика программы и скачиваем ее.
  2. Открываем FileZilla и заполняем поля хост, имя пользователя и пароль в верхней части интерфейса.
  3. Затем кликаем по кнопке «Быстрое соединение», чтобы получить доступ к корневой директории.

Интерфейс FileZilla

FTP-клиенты мало чем отличаются от файловых менеджеров. Большая их часть визуально напоминает Total Commander. Перед вами появится двухпанельный интерфейс: в одной из панелей будут локальные файлы и папки, во второй — файлы и папки хостинга.

Для управления используются горячие клавиши или элементы в верхней панели FileZilla.

Через панель управления хостинга

Я уже говорил ранее, что некоторые провайдеры предоставляют доступ к файлам на сервере через собственное веб-приложение. Расскажу о том, как работает такое приложение у Timeweb (для управления виртуальным хостингом).

  • Открываем сайт Timeweb.
  • Заходим в саму ПУ.
  • Переходим во вкладку «Файловый менеджер».
  • Открываем директорию public_html.

Если вы пользуетесь услугами другого хостинга, то в нем наверняка есть альтернативное схожее решение для управления файлами сервера напрямую через браузер. Можете уточнить у техподдержки или самостоятельно поискать в ПУ пункт с названием «Файловый менеджер».

Через стороннюю панель управления

Некоторые вебмастера используют для управления сайтом программы в духе ISPmanager. Расскажу о переходе в корень виртуального выделенного сервера на ее примере.

  • Заходим в панель ISPmanager.
  • Авторизуемся, используя данные администратора.
  • Открываем меню «Система».
  • Выбираем подпункт «Менеджер файлов».

Через файловый менеджер

В Explorer (Windows) и в Finder (macOS) есть встроенная поддержка протокола FTP. То есть для подключения к серверу не нужно скачивать стороннее ПО. Достаточно ввести FTP-адрес в соответствующее поле файлового менеджера операционной системы.

Доступ к FTP в macOS

В macOS это делается следующим образом:

  • Открываем Finder.
  • Одновременно нажимаем клавиши Cmd + K.
  • Указываем адрес сервера в формате ftp://IP-адрес сайта
  • Кликаем по кнопке «Подключиться».
  • Авторизуемся, используя данные, которые выдал хостинг.
  • Открываем Explorer.
  • Вводим во встроенную поисковую строку ftp://IP-адрес сайта
  • Авторизуемся, используя данные, которые выдал хостинг.

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

Как загружать файлы в корневой каталог?

Загружать файлы в корень сервера можно через одну из панелей управления указанных выше или через FTP-клиент.

  • Открываем FileZilla (мы уже скачали, установили и настроили ее ранее в инструкции по подключению через FTP).
  • Напротив строки «Локальный сайт» вводим путь до файлов на диске, которые надо загрузить в root.
  • Напротив строки «Удаленный сайт» вводим путь до root-каталога. Например, до папки public_html.
  • Выделяем папку, которую нужно перенести, и открываем меню «Файл».
  • В появившемся списке опций выбираем «Загрузить на сервер» или просто жмем на Enter.

В случае с виртуальным хостингом Timeweb достаточно открыть фирменный менеджер файлов через браузер и перетащить в него файлы с жесткого диска. Здесь полноценно поддерживается Drag & Drop. Но такой метод менее удобен, так как он требует держать браузер открытым и отнимает много времени на загрузку большого количества файлов.

На этом ликбез можно заканчивать. Вы узнали, что такое «корень», зачем он нужен и как загрузить в него файлы. Осталось выбрать наиболее удобный способ для подключения к хранилищу сервера и управления им.

Статья, в которой рассмотрим как в php получить путь до корня сайта. Кроме того познакомимся с тем, чем отличается абсолютный путь в PHP и HTML.

Корень (слэш) в HTML и PHP

PHP в отличие от HTML видит файловую систему глубже. В HTML корнем сайта является некоторая директория, которая определяется настройками веб-сервера. Т.е. это определённый каталог в файловой системе, начиная с которого размещаются документы (файлы) этого сайта.

Например, в HTML путь к изображению image1.jpg, которое расположено в каталоге images относительно корня сайта будет иметь следующий вид:


В php слэш (/) обозначает корень файловой системы, а не корень сайта.

Т.е. такая запись в php будет означать, что файл image1.jpg расположен в директории images, которая находится в корне файловой системы.


Чтобы к этому файлу добраться из php необходимо будет проделать более длинный путь. Т.е. сначала добраться до корня сайта (некоторой директории), а потом от него до нужного файла.

Например, на хостинге (в зависимости от хостинга путь до корня сайта может отличаться) путь к файлу будет следующим:


PHP - Абсолютный путь до файла

Например, путь к файлу сайта, который работает на веб-сервере Apache (сборка Денвер) в операционной системе Windows будет следующим:


PHP — Корень сайта

Получить корневую папку сайта в скрипте php можно используя предопределённый (глобальный) массив $_SERVER:


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


// вывести корень сайта

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

Например, скопируем файл image1.jpg, расположенный в корне сайта, в каталог images (/assets/images — путь от корня сайта):


// получить корень сайта
//скопировать файл image1.png в папку images, расположенную в корне сайта
copy($root.'/image1.jpg', $root.'/assets/images/image1.jpg');


4 years, 5 months ago

Can you let me know where the website data/public html folder for my website is located?


  • /var/www/html/
  • /srv/http/
  • /home/${USER}/

If you haven’t setup your server, read about LAMP or LEMP stacks, they’ll get you started.

That being said, most web servers have a standard of configuration for their directory structure when first initializing the website.

Site Content

Also keep in mind, depending on your distro/server version these may differ. But in general the document root for Apache and Nginx (most common opensource web servers) might be in one of these directories:

  • /var/www/
  • /srv/www/
  • /srv/http/
  • /home/${USER}/
  • /usr/share/
  • /usr/local/

So say you are running an Nginx webserver and are looking for content being served when you visit your site you might find it here: /var/www/html/

Server Configuration

To find out exactly where your document root lives, you can look in your servers configuration file. Here you can also modify your web servers configurations, like what port you’ll be serving your site, or change where your document root lives, etc., you might find that config in one of these directories:

  • /etc/apache2/
  • /etc/nginx/
  • /etc/httpd/

To add onto Austin’s post, I’d like to provide some instructions on how to find the configuration file.

The common Apache configuration file path is in/etc/apache2/sites-available/examplesite. Depending on what your developer named the directory, examplesite will vary. To verify the directory name, you would run the command ls -la /etc/apache2/sites-available. The output of that command would look something like this:

total 24
drwxr-xr-x 3 root root 4096 Sep  4 19:54 .
drwxr-xr-x 8 root root 4096 Aug 26 15:25 ..
-rw-r--r-- 1 root root 1332 Feb  3  2019 000-default.conf
-rw-r--r-- 1 root root 6338 Feb  3  2019 default-ssl.conf
drwxr-xr-x 2 root root 4096 Sep  4 19:54 examplesite
# domain:
# public: /var/www/html/

<VirtualHost *:80>
  # Admin email, Server Name (domain name), and any aliases

  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.html index.php
  DocumentRoot /var/www/html/
  # Log file locations
  LogLevel warn
  ErrorLog  /var/www/html/
  CustomLog /var/www/html/ combined

In this output, you’ll want to focus on # Index file and Document Root (where the public files are located). Index files are where you will make modifications to change the look of the front web page. To edit an index file, you’ll have to run the command nano /etc/apache2/sites-available/examplesite/example.conf.

If you get permission denied errors in any part of this process, you’ll need to run the command using sudo before it, and enter the root password of your Linode (not your Manager password). Running a sudo command for editing the example configuration file would look something like this: sudo nano /etc/apache2/sites-available/examplesite/example.conf

In OpenLiteSpeed default configuration it is located in:


Please enter an answer


I’m a blockquote.

I’m a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct

Apache web server is probably the most used web server across platforms including different Linux distributions and Windows. The web server is used to deliver web content and can serve many queries at once.

In this short tutorial, you are going to learn how to modify the root directory for Apache web server. For the purpose of this tutorial, we will use Ubuntu/Debian and RHEL/CentOS/Fedora based installations of the web server.

However the paths and directives are practically the same for other distributions as well, so you will be able to apply the learned in different OSes as well.

To make the necessary changes you need to modify the DocumentRoot directive of the web server. This is the directory from which Apache will read the contents that the visitor will access over browser. Or in other words, this is the directory that forms the tree of directories that will be accessible over web.

The default DocumentRoot for Apache  is:


These paths are described in the Apache’s configuration file.





To change the document root for your Apache web server simply open the corresponding file with your favourite text editor and search for DocumentRoot.

# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
DocumentRoot "/var/www/html"

After that change the path to the new target directory and make sure that Apache is able to read/write in that directory. Once you have modified the DocumentRoot, save the file and restart apache with:

# systemctl restart apache     [For SystemD]
# service httpd restart        [For SysVinit]    

Final thoughts

The change of default document root is an easy task that can be completed in a couple of minutes. When making such changes is important to make sure that you do not make any typos and make sure to always restart Apache after making changes to its configuration file.

Дополнительно:  Несистемный root

Are you looking for what is a root directory of a website? A root directory is a folder on the server or in cPanel that incorporates all of the contents or files of your website. It is the top folder in the directory, usually designated as public_html.

To make it easy, let’s begin this article with what is a root directory of a website and where to find the root directory of a website. Also, read What Is The Difference Between A Database And A Website?

What Is A Root Directory Of A Website

The root directory is a Unix-like operating system, and the root folders are marked with the slash “/”. This folder, which is sometimes referred to as public_html, htdocs, www, or wwwroot, holds the index files index.php, index.html, and default.html.

Among them, the root folder is always on the top of all folders. From the root directory, all the subsequent directories expand outwards. There could be multiple levels and subdirectories between the root directory (level 0) and the bottom-most subdirectory, as discussed in the next section.

Example of root directory: Our website domain is the root directory folder (level 0) and is represented as

The first level or subdirectory could be your pages like us/.

Apart from these, the root directory stores libraries, media files, HTML codes, etc., under different subdirectory root folders. It also incorporates sensitive data or information like robots.txt and sitemap files.

Structure Of A Root Directory

what is a root directory of a website

Remember, all files inside your cPanel or hosting are not root directory folders; there could be settings or installation folders. The root directory folder usually begins from public_html/

Let’s understand it with a simple example of the root directory system of a website.

| Library/
| Templates/
| +-- config.php
+-- Media/
| +-- image1.jpg
| +-- image2.jpg
--- includes/
| +-- style.css
| +-- script.js
+-- index.php

As earlier mentioned, the root directory hierarchy begins from the moment where a visitor reaches your website via a browser. So, in the above example, the root directory folder is public_html/, whereas +– Media/ is the subdirectory or sublevels.

In the end, when a visitor visits your homepage, the +–index.php folder gets active. Remember, the files or folders that are not liable for being publicly exposed, like database login, are always outside the root folder.

How Do I Find Root Directory Of A Website? Where Is Root Directory Of My Website?

After knowing what is a root directory of a website, you probably looking for how to access the root directory. So, I will give you a brief overview to find root directory folders.

Depending on the hosting you are availing of, the root directory files can be accessed through cPanel, web hosting, or VPS hosting. Commonly, you find your root directory files of a website inside the public_html folder.

Method 1. cPanel

The easiest way to find the root directory of a website is by utilizing the cPanel (I’m supposing your site is hosted on cPanel). Nowadays, cPanel becomes the first choice of almost all site owners due to its simplicity.

  • Log in to your cPanel (with username and password).
  • Once logged in, scroll down, and look for the files section.

find root directory of a website

  • Carefully look at the different folders; you can see the public_html folder.

what is a root directory of a website

  • Now, click on the public_html folder, where you can access all the root folders or subdirectories relevant to your website.

Remember, all directories within the public_html folder must have 0755 permissions, and the public_html folder must always have 0750 permissions.

Method 2. VPS Hosting

VPS hosting is a virtualized version of a specialized physical server and has its own processors, memory, and disk storage. If you’re using VPS like DigitalOcean, Vultr, etc., then you can find the root directory using an FTP client like FileZilla.

what is a root directory of a website

How To Find System Root Directory In Windows?

You shouldn’t be confused the root directory of a website with the root directory of a system like Windows. We already discussed what is a root directory of a website and where to find it.

To identify the drivers that are really that are being used, as well as the system log archives and troubleshoot failure dump files, navigate to the system root directory. Let’s see how to find root directory of Windows.

  • Press Window and R key simultaneously; Win+R.
  • Type Cmd in the program front and hit the Enter button.

how to find system directory

  • A Command Window will appear on your screen.
  • Type set systemroot in front of the system user name (as shown in the above screenshot).
  • The next line displays the SystemRoot (or system root directory) of your system; In our case, it is SystemRoot=C:\Windows.

Final Thoughts

It is all about what is a root directory of a website. In this article, we have comprehensively discussed what is root directory folder, why it exists, and how to find root directory of a website.

In simple terms, the root directory is the primary folder of your website’s all content and files. The root directory can be located through cPanel or FTP clients like FileZilla.

Also, it could have multiple subdirectories that depend on your website design and structure. I hope you like this post; any queries and suggestions are welcome.

We all are very familiar with Apache web server, it is a very popular web server to host your web files or your website on the web. Here are some links which can help you to configure Apache web server on your Linux box.

Apache Security Tips
Apache Security and Hardening Tips

Here in this tutorial, I’ll cover some main tips to secure your web server. Before you apply these changes in your web server, you should have some basics of the Apache server.

  1. Document root Directory: /var/www/html or /var/www
  2. Main Configuration file: /etc/httpd/conf/httpd.conf (RHEL/CentOS/Fedora) and /etc/apache2/apache2.conf (Debian/Ubuntu).
  3. Default HTTP Port: 80 TCP
  4. Default HTTPS Port: 443 TCP
  5. Test your Configuration file settings and syntax: httpd -t
  6. Access Log files of Web Server: /var/log/httpd/access_log
  7. Error Log files of Web Server: /var/log/httpd/error_log

1. How to hide Apache Version and OS Identity from Errors

When you install Apache with source or any other package installers like yum, it displays the version of your Apache web server installed on your server with the Operating system name of your server in Errors. It also shows the information about Apache modules installed in your server.

Show Apache Version
Show Apache Version

In above picture, you can see that Apache is showing its version with the OS installed in your server. This can be a major security threat to your web server as well as your Linux box too. To prevent Apache to not to display these information to the world, we need to make some changes in Apache main configuration file.

Open configuration file with vim editor and search for “ServerSignature“, its by default On. We need to Off these server signature and the second line “ServerTokens Prod” tells Apache to return only Apache as product in the server response header on the every page request, It suppress the OS, major and minor version info.

# vim /etc/httpd/conf/httpd.conf (RHEL/CentOS/Fedora)
# vim /etc/apache2/apache2.conf (Debian/Ubuntu)
ServerSignature Off
ServerTokens Prod
# service httpd restart (RHEL/CentOS/Fedora)
# service apache2 restart (Debian/Ubuntu)
Hide Apache Version
Hide Apache Version

2. Disable Directory Listing

By default Apache list all the content of Document root directory in the absence of index file. Please see the image below.

Apache Directory Listing
Apache Directory Listing

We can turn off directory listing by using Options directive in configuration file for a specific directory. For that we need to make an entry in httpd.conf or apache2.conf file.

<Directory /var/www/html>
    Options -Indexes
Hide Apache Directory Listing
Hide Apache Directory Listing

3. Keep updating Apache Regularly

Apache developer community is continuously working on security issues and releasing its updated version with new security options. So It is always recommended to use the latest version of Apache as your web server.

To check Apache version: You can check your current version with httpd -v command.

# httpd -v
Server version: Apache/2.2.15 (Unix)
Server built:   Aug 13 2013 17:29:28
# yum update httpd
# apt-get install apache2

It is also recommended to keep your Kernel and OS updated to the latest stable releases if you are not running any specific application which works only on specific OS or Kernel.

4. Disable Unnecessary Modules

# grep LoadModule /etc/httpd/conf/httpd.conf

# have to place corresponding `LoadModule' lines at this location so the
# LoadModule foo_module modules/
LoadModule auth_basic_module modules/
LoadModule auth_digest_module modules/
LoadModule authn_file_module modules/
LoadModule authn_alias_module modules/
LoadModule authn_anon_module modules/
LoadModule authn_dbm_module modules/
LoadModule authn_default_module modules/
LoadModule authz_host_module modules/
LoadModule authz_user_module modules/
LoadModule authz_owner_module modules/
LoadModule authz_groupfile_module modules/
LoadModule authz_dbm_module modules/
LoadModule authz_default_module modules/
LoadModule ldap_module modules/
LoadModule authnz_ldap_module modules/
LoadModule include_module modules/
LoadModule log_config_module modules/
LoadModule logio_module modules/
LoadModule env_module modules/
LoadModule ext_filter_module modules/

5. Run Apache as separate User and Group

Create Apache User and Group
# groupadd http-web
# useradd -d /var/www/ -g http-web -s /bin/nologin http-web
User http-web
Group http-web

6. Use Allow and Deny to Restrict access to Directories

<Directory />
   Options None
   Order deny,allow
   Deny from all
  1. Options “None” – This option will not allow users to enable any optional features.
  2. Order deny, allow – This is the order in which the “Deny” and “Allow” directives will be processed. Here it will “deny” first and “allow” next.
  3. Deny from all – This will deny request from everybody to the root directory, nobody will be able to access root directory.

7. Use mod_security and mod_evasive Modules to Secure Apache

These two modules “mod_security” and “mod_evasive” are very popular modules of Apache in terms of security.


Where mod_security works as a firewall for our web applications and allows us to monitor traffic on a real time basis. It also helps us to protect our websites or web server from brute force attacks. You can simply install mod_security on your server with the help of your default package installers.

Install mod_security on Ubuntu/Debian
$ sudo apt-get install libapache2-modsecurity
$ sudo a2enmod mod-security
$ sudo /etc/init.d/apache2 force-reload
Install mod_security on RHEL/CentOS/Fedora/
# yum install mod_security
# /etc/init.d/httpd restart

mod_evasive works very efficiently, it takes one request to process and processes it very well. It prevents DDOS attacks from doing as much damage. This feature of mod_evasive enables it to handle the HTTP brute force and Dos or DDos attack. This module detects attacks with three methods.

  1. If so many requests come to a same page in a few times per second.
  2. If any child process trying to make more than 50 concurrent requests.
  3. If any IP still trying to make new requests when its temporarily blacklisted.

mod_evasive can be installed directly from the source. Here, we have an Installation and setup guide of these modules which will help you to set up these Apache modules in your Linux box.

8. Disable Apache’s following of Symbolic Links

Options -FollowSymLinks
# Enable symbolic links
Options +FollowSymLinks

Note: To enable rewrite rules inside “.htaccess” file “AllowOverride All” should be present in the main configuration globally.

9. Turn off Server Side Includes and CGI Execution

We can turn off server side includes (mod_include) and CGI execution if not needed and to do so we need to modify main configuration file.

Options -Includes
Options -ExecCGI

We can do this for a particular directory too with Directory tag. Here In this example, we are turning off Includes and Cgi file executions for “/var/www/html/web1” directory.

<Directory "/var/www/html/web1">
Options -Includes -ExecCGI

Here are some other values with can be turned On or off with Options directive.

  1. Options All – To enable All options at once. This is the default value, If you don’t want specify any values explicitly in Apache conf file or .htaccess.
  2. Options IncludesNOEXEC – This option allows server side includes without the execute permission to a command or cgi files.
  3. Options MultiViews – Allows content negotiated multiviews with mod_negotiation module.
  4. Options SymLinksIfOwnerMatch – It’s similar to FollowSymLinks. But, this will follow only when the owner is the same between the link and the original directory to which it is linked.

10. Limit Request Size

By default Apache has no limit on the total size of the HTTP request i.e. unlimited and when you allow large requests on a web server its possible that you could be a victim of Denial of service attacks. We can Limit the requests size of an Apache directive “LimitRequestBody” with the directory tag.

You can set the value in bytes from 0 (unlimited) to 2147483647 (2GB) that are allowed in a request body. You can set this limit according to your site needs, Suppose you have a site where you allows uploads and you want to limit the upload size for a particular directory.

<Directory "/var/www/myweb1/user_uploads">
   LimitRequestBody 512000

11. Protect DDOS attacks and Hardening

Well, it’s true that you cannot completely protect your web site from DDos attacks. Here are some directives which can help you to have a control on it.

  1. TimeOut : This directive allows you to set the amount of time the server will wait for certain events to complete before it fails. Its default value is 300 secs. It’s good to keep this value low on those sites which are subject to DDOS attacks. This value totally depends on kind of request you are getting on your website. Note: It could pose problems with come CGI scripts.
  2. MaxClients : This directive allows you to set the limit on connections that will be served simultaneously. Every new connection will be queued up after this limit. It is available with Prefork and Worker both MPM. The default value of it is 256.
  3. KeepAliveTimeout : Its the amount of time the server will wait for a subsequent request before closing the connection. Default value is 5 secs.
  4. LimitRequestFields : It helps us to set a limit on the number of HTTP request’s header fields that will be accepted from the clients. Its default value is 100. It is recommended to lower this value if DDos attacks are occurring as a result of so many http request headers.
  5. LimitRequestFieldSize : It helps us to set a size limit on the HTTP Request header.

12. Enable Apache Logging

To do so you need to include the mod_log_config module. There are three main logging-related directives available with Apache.

  1. TransferLog: Creating a log file.
  2. LogFormat : Specifying a custom format.
  3. CustomLog : Creating and formatting a log file.

You can also use them for a particular website it you are doing Virtual hosting and for that you need to specify it in the virtual host section. For example, here is the my website virtual host configuration with logging enabled.

<VirtualHost *:80>
DocumentRoot /var/www/html/
DirectoryIndex index.htm index.html index.php
ErrorDocument 404 /story.php
ErrorLog /var/log/httpd/example.com_error_log
CustomLog /var/log/httpd/example.com_access_log combined

13. Securing Apache with SSL Certificates

Last, but not the least SSL certificates, you can secure your all the communication in an encrypted manner over the Internet with SSL certificate. Suppose you have a website in which people login by proving their Login credentials or you have an E- Commerce website where people provides their bank details or Debit/Credit card details to purchase products, by default your web server send these details in plain – text format but when you use SSL certificates to your websites, Apache sends all this information in encrypted text.

You can purchase SSl certificates from So many different SSL providers like If you are running a very small web business and do not willing to purchase an SSL certificate you can still assign a Self signed certificate to your website. Apache uses the mod_ssl module to support SSL certificate.

# openssl genrsa -des3 -out 1024
# openssl req -new -key -out exmaple.csr
# openssl x509 -req -days 365 -in -signkey -out
        SSLEngine on
        SSLCertificateFile /etc/pki/tls/certs/
        SSLCertificateKeyFile /etc/pki/tls/certs/
        SSLCertificateChainFile /etc/pki/tls/certs/sf_bundle.crt
        ServerAdmin [email protected]
        DocumentRoot /var/www/html/example/
        ErrorLog /var/log/httpd/
        CustomLog /var/log/httpd/ common

Open up your browser, type, and you will be able to see the new self-signed certificate.

This guide is the first of a four-part series. Parts One and Two will walk you through installing NGINX Open Source from the NGINX repositories and making some configuration changes to increase performance and security. Parts Three and Four set up NGINX to serve your site over HTTPS and harden the TLS connection.

Before You Begin

  • You will need root access to the system, or a user account with sudo privilege.
  • Set your system’s hostname.
  • Update your system.

Install NGINX

Stable Versus Mainline

The first decision to make about your installation is whether you want the Stable or Mainline version of NGINX Open Source. Stable is recommended, and will be what this series of guides uses. More on NGINX versions here.

Binary Versus Compiling from Source

There are three primary ways to install NGINX Open Source:

  • A pre-built binary from your Linux distribution’s repositories. This is the easiest installation method because you use your package manager to install the nginx package. However, for distributions which provide binaries (as opposed to build scripts), you’ll be running an older version of NGINX than the current stable or mainline release. Patches can also be slower to land in distro repositories from upstream.

  • A pre-built binary from NGINX Inc.’s repository. This is the installation method used in this series. It’s still an easy installation process which only requires that you add the repository to your system and then install as normal. This method has the benefit of the most vanilla, upstream configuration by default, with quicker updates and newer releases than a Linux distribution’s repository. Compile-time options often differ from those of the NGINX binary in distribution repositories, and you can use nginx -V to see which your binary was built with.

Installation Instructions

Configuration Notes

As use of the NGINX web server has grown, NGINX, Inc. has worked to distance NGINX from configurations and terminology that were used in the past when trying to ease adoption for people already accustomed to Apache.

Sure, it can. The NGINX packages in Debian and Ubuntu repositories have changed their configurations to this for quite a while now, so serving sites whose configuration files are stored in /sites-available/ and symlinked to /sites-enabled/ is certainly a working setup. However it is unnecessary, and the Debian Linux family is the only one which does it. Do not force Apache configurations onto NGINX.

NGINX Configuration Best Practices

There is a large variety of customizations you can do to NGINX to fit it better to your needs. Many of those will be exclusive to your use case though; what works great for one person may not work at all for another.

This series will provide configurations that are general enough to be useful in just about any production scenario, but which you can build on for your own specialized setup. Everything in the section below is considered a best practice and none are reliant on each other. They’re not essential to the function of your site or server, but they can have unintended and undesirable consequences if disregarded.

Two quick points:

  • Before going further, first preserve the default nginx.conf file so you have something to restore to if your customizations get so convoluted that NGINX breaks.

      cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup-original
  • After implementing a change below, reload your configuration with:

      nginx -s reload

Use Multiple Worker Processes

worker_processes auto;

Disable Server Tokens

NGINX’s version number is visible by default with any connection made to the server, whether by a successful 201 connection by cURL, or a 404 returned to a browser. Disabling server tokens makes it more difficult to determine NGINX’s version, and therefore more difficult for an attacker to execute version-specific attacks.

Server tokens enabled:

NGNINX server tokens enabled

Server tokens disabled:

NGINX server tokens disabled

server_tokens off;

Set Your Site’s Root Directory

This series will use /var/www/ in its examples. Replace where you see it with the IP address or domain name of your Linode.

  1. root /var/www/;
  2. Then create that directory:

    mkdir -p /var/www/

Serve Content Over IPv4 and IPv6

Default NGINX configurations listen on port 80 and on all IPv4 addresses. Unless you intend your site to be inaccessible over IPv6 (or are unable to provide it for some reason), you should tell NGINX to also listen for incoming IPv6 traffic.

listen [::]:80;

If your site uses SSL/TLS, you would add:

listen [::]:443 ssl;

You can also specify your Linode’s public IP addresses for NGINX to listen on. For example, the line would then be listen;.

Static Content Compression

You do not want to universally enable gzip compression because, depending on your site’s content and whether you set session cookies, you risk vulnerability to the CRIME and BREACH exploits.

Compression has been disabled by default in NGINX for years now, so it’s not vulnerable to CRIME out of the box. Modern browsers have also taken steps against these exploits, but web servers can still be configured irresponsibly.

On the other hand, if you leave gzip compression totally disabled, you rule out those vulnerabilities and use fewer CPU cycles, but at the expense of decreasing your site’s performance. There are various server-side mitigations possible and the release of TLS 1.3 will further contribute to that. For now, and unless you know what you’re doing, the best solution is to compress only static site content such as images, HTML, and CSS.

gzip          on;
gzip_types    text/html text/plain text/css image/*;
File: /etc/nginx/conf.d/
File: /etc/nginx/conf.d/

Configuration Recap

To summarize where we are so far:

  • The stable version of NGINX Open Source was installed from the repository.

  • One basic website is accessible:

    • The root directory is located at /var/www/

    • The configuration file is located at /etc/nginx/conf.d/

      File: /etc/nginx/conf.d/
  • File: /etc/nginx/nginx.conf

(Slightly More) Advanced Configurations

By now you should have a basic NGINX installation and a some foundational settings to get you started. For slightly more advanced configurations, yet still applicable to anyone hosting a site on a Linode, see Part 2 of this series: (Slightly more) Advanced Configurations for NGINX

Дополнительно:  How to root the bluestacks
Оцените статью
Master Hi-technology
Добавить комментарий