Компьютерный форум OSzone.net  

Компьютерный форум OSzone.net (http://forum.oszone.net/index.php)
-   Вебмастеру (http://forum.oszone.net/forumdisplay.php?f=22)
-   -   [решено] Apache It works! (http://forum.oszone.net/showthread.php?t=305368)

Rubichek 13-09-2015 18:39 2552753

Apache It works!
 
Здравствуйте, подскажите пж как убрать It works! если перейти по IP отображается страница

It works!

This is the default web page for this server.

The web server software is running but no content has been added, yet.

как убрать например сделать ошибку 404

Habetdin 13-09-2015 19:35 2552771

Rubichek, какая версия Apache, платформа? Для Apache 2.4.x на Linux: конфигурация хоста по умолчанию описана в файле /etc/apache2/sites-available/000-default.conf, в нём можно найти указание папку с файлом "It Works!", ищите по "DocumentRoot". Значение по умолчанию обычно /var/www или /var/www/html.
Цитата:

Цитата Rubichek
например сделать ошибку 404 »

Можно запретить доступ к папке - будет ошибка 403:
Код:

DocumentRoot "/var/www/example"

<Directory "/var/www/example">
        Deny from all
</Directory>


Rubichek 13-09-2015 20:28 2552796

Server version: Apache/2.2.22 (Debian) в /var/www лежит index.html c содержанием
Цитата:

Цитата Rubichek
It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet. »

Если запретить доступ к /var/www/ не будут работать остальные сайты! Хочу что бы когда человек введет ip сервак то что бы ошибку получал или может запрос логина и пароля!

Habetdin 13-09-2015 20:52 2552799

Цитата:

Цитата Rubichek
Если запретить доступ к /var/www/ не будут работать остальные сайты! »

Запрещаете только в пределах VirtualHost по умолчанию? Приведите содержимое конфигов из /etc/apache2/sites-available/ для облегчения помощи :)

Rubichek 13-09-2015 22:49 2552829

etc/apache2/sites-available/default

Скрытый текст
<VirtualHost *:80>
ServerAdmin webmaster@localhost

DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>


Habetdin 14-09-2015 17:45 2553093

Rubichek, добавьте в эту конфигурацию доп. секцию VirtualHost, заменив выделенный IP на свой:
Код:

<VirtualHost *:80>
        ServerName 123.123.123.123
        Redirect 403 /
        ErrorDocument 403 "Access denied"
        DocumentRoot /dev/null/
        UseCanonicalName Off
        UserDir disabled
</VirtualHost>

А в существующей секции VirtualHost перечислите разрешенные доменные имена, будет что-то вроде:
Код:

<VirtualHost *:80>
        # основной домен
        ServerName example.com
        # дополнительные (через пробел, если несколько)
        ServerAlias www.example.com test.example.com

        ServerAdmin webmaster@localhost
        ...


Rubichek 24-09-2015 00:00 2556908

когда перегружаю apache2 ошибка

Скрытый текст

Warning: DocumentRoot [/dev/null/] does not exist
Syntax error on line 39 of /etc/apache2/sites-enabled/000-default:
Invalid command 'UserDir', perhaps misspelled or defined by a module not included in the server configuration
Action 'configtest' failed.
The Apache error log may have more information.
failed!


Habetdin - может не верно вас понял добавляем тут в конце

etc/apache2/sites-available/default

или

etc/apache2/sites-enabled/000-default

Скрытый текст
<VirtualHost *:80>
ServerName 123.123.123.123
Redirect 403 /
ErrorDocument 403 "Access denied"
DocumentRoot /dev/null/
UseCanonicalName Off
UserDir disabled
</VirtualHost>

Habetdin 24-09-2015 18:23 2557240

Цитата:

Цитата Rubichek
Invalid command 'UserDir' »

Удалите/закомментируйте строчку с UserDir.
Цитата:

Цитата Rubichek
etc/apache2/sites-available/default
или
etc/apache2/sites-enabled/000-default »

В тот файл, который уже есть, судя по пятому посту - default. Будет что-то вроде этого:
Код:

<VirtualHost *:80>
        ServerName 123.123.123.123
        Redirect 403 /
        ErrorDocument 403 "Access denied"
        DocumentRoot /dev/null/
        UseCanonicalName Off
        # UserDir disabled
</VirtualHost>
# оригинальное содержимое с прописанными доменами
<VirtualHost *:80>
        # основной домен
        ServerName example.com
        # дополнительные (через пробел, если несколько)
        ServerAlias www.example.com test.example.com
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>


Rubichek 24-09-2015 19:22 2557259

Habetdin - спасибо работает когда захожу по внешнему ip Access denied. Но и когда захожу на сайт или phpmyadmin тоже Access denied

Habetdin 25-09-2015 18:31 2557677

Rubichek, домены в ServerName и ServerAlias старой секции VirtualHost прописали? И попробуйте поменять местами две секции VirtualHost - не уверен, как Apache их обрабатывает :tomato2:

Rubichek 25-09-2015 18:52 2557688

Часть конфига. Первый virtualhost пробовал ставить в конец та же ошибка.

Скрытый текст
<VirtualHost *:80>
ServerName 11.111.11.11
Redirect 403 /
ErrorDocument 403 "Access denied"
DocumentRoot /dev/null/
#UseCanonicalName Off
# UserDir disabled
</VirtualHost>
<VirtualHost *:80>
# основной домен
ServerName test.com
# дополнительные (через пробел, если несколько)
ServerAlias test.com www.test.com
ServerAdmin webmaster@localhost

DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all


Habetdin 25-09-2015 23:05 2557754

Цитата:

Цитата Rubichek
#UseCanonicalName Off »

Почему закомментировали эту строку? Без отключения UseCanonicalName запросы с SERVER_NAME, отличным от IP 11.111.11.11, все равно могут обработаны этой секцией VirtualHost.
Цитата:

Цитата Rubichek
ServerAlias test.com www.test.com »

Здесь не нужен test.com, он задан как основной в ServerName, в alias достаточно версии с www.

Rubichek 26-09-2015 17:30 2557916

Access denied - если захожу на сайты всеравно

Habetdin 28-09-2015 08:04 2558411

Rubichek, очень странно. Раскомментировали строчку "UseCanonicalName Off", перезагрузили конфиг?
Должно работать, сейчас даже проверил по-быстрому на виртуалке - по IP доступа нет, по разрешенным доменам - есть.
Установил Debian, в нём - Apache2 на виртуалку с IP 172.16.0.42. На этот же IP направил домены test.local, example.local и unused.local. Проверил - "It works!" Внес изменения в конфигурацию:
Было
Код:

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port t$
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

Стало
Код:

<VirtualHost *:80>
        ServerName 172.16.0.42
        Redirect 403 /
        ErrorDocument 403 "Access denied"
        DocumentRoot /dev/null/
        UseCanonicalName Off
        # UserDir disabled # mod_userdir не включен
</VirtualHost>
<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port t$
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        ServerName test.local
        ServerAlias example.local


        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>


Перезапустил веб-сервер (service apache2 restart) - по IP "Access denied", по обоим доменам из конфигурации (test и example) - "It works!". А вот по unused.local, который для теста не прописал - та же картина, что при доступе по IP - "Access denied" (что ожидаемо). Так что проблема может быть в неопознанном домене.
Заодно проверил, влияет ли в данном случае на результат порядок секций VirtualHost - оказалось, без разницы.

Проблема может быть в неопознанном домене. A-запись test.com указывает на 11.111.11.11? Apache не за проксирующим сервером?
Давайте проверим, какой SERVER_NAME получается в ходе работы Apache: закомментируйте в конфиге строчку «ErrorDocument 403 "Access denied"», после этого страница ошибки будет с дополнительной информацией, интересующая нас - внизу, под чертой (что-то вроде «Apache/2.2.15 (CentOS) Server at fanlab.org Port 80»).
Что у вас там при доступе по домену?

Rubichek 28-09-2015 14:18 2558529

Forbidden

You don't have permission to access /test.com/ on this server.

вы правите этот конфиг etc/apache2/sites-available/default

Habetdin 28-09-2015 17:22 2558597

В ходе дискуссии в ЛС выяснилось, что нужно заблокировать не доступ по IP, а доступ к IP с пустым pathname (а точнее, отключить листинг файлов, который вылез при удалении html-файла с "It Works!" (/var/www/html/index.html), для корневого каталога)
Решение - намного проще...
Один минус, добавленный в изначальный конфиг:
Код:

<VirtualHost *:80>
ServerAdmin webmaster@localhost

DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
# минус перед Indexes:
Options -Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>


Rubichek 28-09-2015 18:43 2558622

Habetdin Спасибо большое.


Время: 06:31.

Время: 06:31.
© OSzone.net 2001-