RTFM.WIKI

Ordnung muß sein. Ordnung über alles (18+)

Инструменты пользователя

Инструменты сайта


Stylesheet conf/userstyle.css not found, please contact the developer of "dokuwiki_2024" template.
linux:apache:apache_tnt

Различия

Показаны различия между двумя версиями страницы.

Ссылка на это сравнение

Следующая версия
Предыдущая версия
linux:apache:apache_tnt [2021/03/09 01:25] – внешнее изменение 127.0.0.1linux:apache:apache_tnt [2022/04/19 18:36] (текущий) dx
Строка 1: Строка 1:
 +====== Трюки с Apache ======
  
 +===== HowTo - Как сделать xyz? =====
 +
 +==== Редирект 301 http в https ====
 +
 +<code>
 +<VirtualHost *:80> 
 +  ServerName foobar.com
 +  ServerAlias www.foobar.com
 +  #Redirect permanent / https://foobar.com/
 +  Redirect 301 / https://foobar.com/
 +</VirtualHost>
 +
 +<VirtualHost *:443>
 +  ServerName foobar.com
 +  ServerAlias www.foobar.com
 +  Protocols h2 http/1.1
 +</VirtualHost>
 +</code>
 +
 +если дополнительно надо убрать www, то добавляем vhost 443
 +
 +<code>
 +  <If "%{HTTP_HOST} == 'www.foobar.com'">
 +    Redirect permanent / https://foobar.com/
 +  </If>
 +</code>
 +
 +также через htaccess
 +
 +<code>
 +RewriteEngine on
 +RewriteCond %{HTTPS} off
 +RewriteRule ^(.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301]
 +</code>
 +
 +либо с указанием домена явно
 +
 +<code>
 +RewriteEngine On
 +RewriteCond %{HTTPS} off
 +RewriteRule ^(.*)$ https://foobar.com/$1 [L,R=301]
 +</code>
 +
 +и убираем www
 +
 +<code>
 +RewriteCond %{HTTPS} off [OR]
 +RewriteCond %{HTTP_HOST} ^www\.foobar\.com [NC]
 +RewriteRule ^(.*)$ https://foobar.com/$1 [L,R=301]
 +</code>
 +
 +==== AH00558: apache2: Could not reliably determine the server's fully qualified domain name ====
 +
 +AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using hola.foobar.com. Set the 'ServerName' directive globally to suppress this message
 +
 +Добавить в ''/etc/apache2/apache2.conf'' или ''/etc/httpd/conf/httpd.conf''
 +
 +<code>ServerName 127.0.0.1</code>
 +
 +==== AH00548: NameVirtualHost has no effect ====
 +
 +AH00548: NameVirtualHost has no effect and will be removed in the next release /etc/apache2/ports.conf:5
 +
 +[[https://httpd.apache.org/docs/2.4/mod/core.html#namevirtualhost|Это не ошибка]]
 +
 +<blockquote>Prior to 2.3.11, NameVirtualHost was required to instruct the server that a particular IP address and port combination was usable as a name-based virtual host. In 2.3.11 and later, any time an IP address and port combination is used in multiple virtual hosts, name-based virtual hosting is automatically enabled for that address.
 +
 +This directive currently has no effect.</blockquote>
 +
 +==== Залогиниться в закрытую часть htpasswd ====
 +
 +<code>https://user:[email protected]/area51/</code>
 +
 +Без https так лучше не делать.
 +
 +==== Отличие между AddHandler и SetHandler ====
 +
 +Источник: http://blog.brainf.net/servernoe-administrirovanie/raznica-mezhdu-add-handler-i-sethandler/
 +
 +Веб-сервер apache достаточно прост в настройке. Но тут как и везде есть свои ньюансы. Вы можете заставить его интерпретировать php-файлы c помощью директивы SetHandler либо c помощью AddHandler. На первый взгляд кажется нет никакой разницы, но она на самом деле есть и очень существенна.
 +
 +А все дело в том что apache допускает у файла несколько расширений. И если вы задаете директиву AddHandler — то вы просто указываете что выполнение как php — это только один из возможных способов обработки файла. В то время как SetHanler указывает однозначное соответствие. Что это означает на практике? Все просто. Рассмотрим следующий случай. У вас есть форма, позволяющяя загружать пользовательские текстовые файлы и при загрузке вы просто проверяете расширение файла. В случае с AddHandler злоумышленнику достаточно назвать файл shell.php.txt и ваш валидатор его спокойно пропустит, а Apache успешно выполнит как php-скрипт
 +
 +==== Проверка нагрузки на веб-сервер ====
 +
 +Число процессов веб-сервера Apache
 +
 +<code>
 +# ps aux | grep httpd | wc -l
 +# ps aux | grep apache2 | wc -l
 +</code>
 +
 +Число соединений на 80 порту
 +
 +<code># netstat -na | grep :80 | wc -l</code>
 +
 +Число соединений на 80 порту в статусе SYN
 +
 +<code># netstat -na | grep :80 | grep syn</code>
 +
 +Количество соединений на 80 порту с каждого IP
 +
 +<code># netstat -na | grep :80 | sort | uniq -c | sort -nr | more</code>
 +
 +Общее количество соединений с каждого IP
 +
 +<code># netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n</code>
 +
 +==== Как изменить имя веб-сервера ====
 +
 +Иногда внизу страниц 403/404/500 можно заметить нечто вроде **Apache/2.4.6 (CentOS) Server at 192.168.13.77 Port 80**
 +
 +Если это включено намерено, но хочется изменить текст, то на помощь придет [[https://modsecurity.org/|mod_security]]
 +
 +Ставим модуль
 +
 +<code># yum install mod_security</code>
 +
 +Добавляем в файл ''httpd.conf''
 +
 +<code>
 +ServerTokens Full
 +ServerSignature On
 +SecServerSignature "Microsoft Teapot"
 +</code>
 +
 +И перезапускаем веб-сервер
 +
 +<code>systemctl restart httpd</code>
 +
 +Результат
 +
 +{{:linux:apache:apache_server_signature_modsec.png?nolink|}}
 +
 +Конечно же **mod_security** создан не для подобных шуток, а для защиты веб-приложений, но есть и такая вот фича у него.
 +
 +==== Как перевыпустить самоподписанный сертификат используя openssl ====
 +
 +<code>
 +# uname -a
 +Linux cool.host.name 2.6.32-279.el6.i686 #1 SMP Fri Jun 22 10:59:55 UTC 2012 i686 i686 i386 GNU/Linux
 +</code>
 +
 +Истёк срок самоподписаного сертификата в Apache
 +
 +<code>
 +# echo | openssl s_client -connect IP:443 2>/dev/null | openssl x509 -noout -dates
 +notBefore=Jan 10 15:19:56 2013 GMT
 +notAfter=Jan 10 15:19:56 2014 GMT
 +</code>
 +
 +Смотрим где находятся настройки связанные с SSL в Apache
 +
 +<code>
 +# grep SSLCertificate /etc/httpd/conf.d/ssl.conf
 +# Point SSLCertificateFile at a PEM encoded certificate.  If
 +SSLCertificateFile /etc/pki/tls/certs/localhost.crt
 +SSLCertificateKeyFile /etc/pki/tls/private/localhost.key
 +#   Point SSLCertificateChainFile at a file containing the
 +#   the referenced file can be the same as SSLCertificateFile
 +#SSLCertificateChainFile /etc/pki/tls/certs/server-chain.crt
 +</code>
 +
 +Всегда делаем копию данных
 +
 +<code>
 +# cp /etc/pki/tls/private/localhost.key /root/
 +# cp /etc/pki/tls/certs/localhost.crt /root/
 +</code>
 +
 +Создаём новый сертификат на 10 лет (3652 дня)
 +
 +<code>
 +# openssl req -new -days 3652 -x509 -nodes -newkey rsa:2048 -out /etc/pki/tls/certs/localhost.crt -keyout /etc/pki/tls/private/localhost.key
 +Generating a 2048 bit RSA private key
 +......................+++
 +........................................................................................................................+++
 +writing new private key to '/etc/pki/tls/private/localhost.key'
 +-----
 +You are about to be asked to enter information that will be incorporated
 +into your certificate request.
 +What you are about to enter is what is called a Distinguished Name or a DN.
 +There are quite a few fields but you can leave some blank
 +For some fields there will be a default value,
 +If you enter '.', the field will be left blank.
 +-----
 +Country Name (2 letter code) [XX]:
 +State or Province Name (full name) []:
 +Locality Name (eg, city) [Default City]:Frankfurt
 +Organization Name (eg, company) [Default Company Ltd]:
 +Organizational Unit Name (eg, section) []:
 +Common Name (eg, your name or your server's hostname) []:
 +Email Address []:
 +</code>
 +
 +Возможно потребуется выставить права
 +
 +<code>
 +# chmod 600 /etc/pki/tls/certs/localhost.crt
 +# chmod 600 /etc/pki/tls/private/localhost.key
 +</code>
 +
 +Перезапускаем веб-сервер
 +
 +<code># service httpd restart</code>
 +
 +Проверяем новый сертификат
 +
 +<code>
 +# echo | openssl s_client -connect 185.72.244.81:443 2>/dev/null | openssl x509 -noout -dates 
 +notBefore=Jan 20 08:06:16 2017 GMT
 +notAfter=Jan 20 08:06:16 2027 GMT
 +</code>
 +
 +==== Как сделать, чтобы сайт открывался только по доменному имени ====
 +
 +Задача: необходимо, чтобы сайт открывался только по доменному имени, а не по IP-адресу.
 +
 +Решение:
 +
 +<code>
 +<virtualhost ip_addr:80>
 +redirect permanent / http://foobar.com/
 +</virtualhost>
 +</code>
 +
 +Где http://foobar.com/ – нужный сайт.
 +
 +==== http authentication ====
 +
 +<code>
 +<IfModule mod_authn_file.c>
 +  # Apache 2.4 or later
 +  AuthType Basic
 +  AuthName "Please provide username and password"
 +  AuthBasicProvider file
 +  AuthUserFile "/var/www/vhosts/site.tld/passwd/htaccess.passwd"
 +  Require valid-user
 +</IfModule>
 +
 +<IfModule mod_auth.c>
 +  # Apache 2.2 or lower
 +  AuthType Basic
 +  AuthName "Please provide username and password"
 +  AuthUserFile "/var/www/vhosts/site.tld/passwd/htaccess.passwd"
 +  Require valid-user
 +</IfModule>
 +</code>
 +
 +==== Редирект 301 domain.com в www.domain.com используя mod_rewrite ====
 +
 +via http://www.adminsehow.com/2009/05/redirect-301-domaincom-to-wwwdomaincom-using-mod_rewrite/
 +
 +<code>
 +Options +FollowSymLinks
 +RewriteEngine On
 +rewritecond %{http_host} ^domain.com [NC]
 +rewriterule ^(.*)$ http://www.domain.com/$1 [R=301,NC,L]
 +</code>
 +
 +==== Как посмотреть список загруженных модулей Apache ====
 +
 +<code># apachectl -M</code>
 +
 +или
 +
 +<code># apachectl -t -D DUMP_MODULES</code>
 +
 +или (для RHEL, Fedora, CentOS)
 +
 +<code># httpd -M</code>
 +
 +UPD бонус - посмотреть настроенные виртуальные хосты
 +
 +<code># httpd -t -D DUMP_VHOSTS</code>
 +
 +==== Как посмотреть uptime веб-сервера? ====
 +
 +<code>
 +# ps -eo comm,etime | grep httpd
 +httpd           26-08:33:00
 +httpd                 01:09
 +httpd              20:14:45
 +httpd              20:14:45
 +httpd              20:14:45
 +httpd              20:14:45
 +httpd              20:14:45
 +httpd              20:14:45
 +httpd              20:14:45
 +httpd              20:14:45
 +httpd              20:14:45
 +httpd              20:14:45
 +httpd              20:14:34
 +httpd              19:45:45
 +httpd              19:40:57
 +httpd              19:40:56
 +httpd              19:40:56
 +</code>
 +
 +Если включен [[http://httpd.apache.org/docs/2.2/mod/mod_status.html|mod_status]]
 +
 +<code># apachectl status
 +The 'links' package is required for this functionality.
 +# yum install links
 +</code>
 +
 +==== logrotate, uptime ====
 +
 +У сервера uptime год, а вот Apache постоянно перезагружается?
 +
 +В error_log следующее
 +
 +<code>
 +[Sun Jun 19 04:41:01 2016] [notice] SIGHUP received.  Attempting to restart
 +[Sun Jun 26 03:11:03 2016] [notice] SIGHUP received.  Attempting to restart
 +</code>
 +
 +Как посмотреть, когда был перезагружен Apache
 +
 +<code>
 +# grep resuming /var/log/httpd/error_log
 +[Sun Jun 26 03:11:04 2016] [notice] Apache/2.2.15 (Unix) configured -- resuming normal operations
 +</code>
 +
 +Никакого бага или ошибки здесь нет, это такая фича. При запуске ротации логов Apache делает <del>restart</del> reload.
 +
 +Файл ''/etc/logrotate.d/httpd''
 +
 +<code>
 +/var/log/httpd/*log {
 +    missingok
 +    notifempty
 +    sharedscripts
 +    delaycompress
 +    postrotate
 +        /sbin/service httpd reload > /dev/null 2>/dev/null || true
 +    endscript
 +}
 +</code>
 +
 +Как сделать, чтобы Apache не перезапускался и что надо знать про logrotate простому человеку?
 +
 +Например так - http://httpd.apache.org/docs/2.2/logs.html#piped или же использовать ''copytruncate'' ([[http://serverfault.com/questions/404916/logrotate-httpd-apache-logs-possible-without-reloading-httpd-after-log-purge|
 +Logrotate httpd (apache) logs - Possible without reloading httpd after log purge?]])
 +
 +Загадочный cron.daily, а также .hourly и .weekly
 +
 +Вы когда-нибудь задавались вопросом, а когда собственно они выполняются? Ответ нашёл [[https://serverfault.com/questions/135906/when-does-cron-daily-run|здесь]].
 +
 +Разные панели Vesta/ISPmgr как раз таки записывают свои правила ротации в cron.daily
 +
 +Ещё интересное
 +  * https://stackoverflow.com/questions/20162176/centos-linux-setting-logrotate-to-maximum-file-size-for-all-logs
 +  * https://stackoverflow.com/questions/14858752/logrotate-to-clean-up-date-stamped-files
 +
 +UPD
 +
 +Читай МАНтру и будешь труЪ!
 +
 +**Проблема.** Настроил в отдельном файле в "/etc/logrotate.d" ротацию своего приложения через каждый час, а она не работает.
 +
 +<code>
 +/tmp/last_logs {
 +  hourly
 +  rotate 5
 +</code>
 +
 +**В чём же дело?**
 +
 +//Log files are rotated every hour. Note that usually logrotate is configured to be run by cron daily. You have to change this configuration and run logrotate hourly to be able to really rotate logs hourly.//
 +
 +**Как быть?** Скопировать ''/etc/cron.daily/logrotate'' в ''/etc/cron.hourly/''. В Debian работает.
 +
 +===== Ошибки, баги, глюки =====
 +
 +==== handle($request); $response->send(); ====
 +
 +...$kernel->terminate($request, $response);
 +
 +Решение
 +
 +<code>apt install libapache2-mod-php7.4</code>
 +
 +==== perhaps misspelled or defined ====
 +
 +**Err:** Invalid command 'Header', perhaps misspelled or defined by a module not included in the server configuration \\
 +**Fix:** a2enmod headers
 +
 +**Err:** Invalid command 'SSLProxyEngine', perhaps misspelled or defined by a module not included in the server configuration \\
 +**Fix:** a2enmod ssl 
 +
 +**Err:** Invalid command 'ProxyPass', perhaps misspelled or defined by a module not included in the server configuration \\
 +**Fix:** a2enmod proxy
 +
 +==== Config variable ${APACHE_RUN_USER} is not defined ====
 +
 +Ошибка
 +
 +<code>
 +# apache2 -V
 +[Fri Apr 20 07:55:30.472544 2018] [core:warn] [pid 11978] AH00111: Config variable ${APACHE_LOCK_DIR} is not defined
 +[Fri Apr 20 07:55:30.472816 2018] [core:warn] [pid 11978] AH00111: Config variable ${APACHE_PID_FILE} is not defined
 +[Fri Apr 20 07:55:30.472946 2018] [core:warn] [pid 11978] AH00111: Config variable ${APACHE_RUN_USER} is not defined
 +[Fri Apr 20 07:55:30.473054 2018] [core:warn] [pid 11978] AH00111: Config variable ${APACHE_RUN_GROUP} is not defined
 +[Fri Apr 20 07:55:30.473197 2018] [core:warn] [pid 11978] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
 +[Fri Apr 20 07:55:30.502162 2018] [core:warn] [pid 11978] AH00111: Config variable ${APACHE_LOCK_DIR} is not defined
 +[Fri Apr 20 07:55:30.503294 2018] [core:warn] [pid 11978] AH00111: Config variable ${APACHE_RUN_DIR} is not defined
 +[Fri Apr 20 07:55:30.503906 2018] [core:warn] [pid 11978] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
 +AH00526: Syntax error on line 74 of /etc/apache2/apache2.conf:
 +Invalid Mutex directory in argument file:${APACHE_LOCK_DIR}
 +</code>
 +
 +Решение
 +
 +<code>
 +# source /etc/apache2/envvars
 +# apache2 -t
 +Syntax OK
 +</code>
 +
 +==== httpd.itk: could not open error log file ====
 +
 +Starting httpd: (2)No such file or directory: httpd.itk: could not open error log file /etc/httpd/logs/error_log.
 +Unable to open logs
 +
 +В ''/var/log/'' нет каталога httpd. Создаём.
 +
 +<code>mkdir /var/log/httpd</code>
 +
 +==== module remoteip_module is already loaded, skipping ====
 +
 +Смотрим где у нас дублируется **LoadModule**
 +
 +<code># grep remoteip_module -rI /etc/httpd/*</code>
 +
 +==== (98)Address already in use: make_sock: could not bind to address 80 ====
 +
 +via http://www.webune.com/forums/98address-already-in-use-make-sock-could-not-bind-to-address-80-t1091.html
 +
 +<code>
 +# for i in `ps auwx | grep -i nobody | awk {'print $2'}`; do kill -9 $i; done
 +# for i in `lsof -i :80 | grep http | awk {' print $2'}`; do kill -9 $i; done
 +# for i in `lsof -i :80 | grep http | awk {' print $2'}`; do kill -9 $i; done
 +# service httpd restart
 +</code>
 +
 +или так
 +
 +<code># fuser -k -n tcp 80</code>
 +
 +==== PHP Warning: require_once(): Unable to allocate memory for pool ====
 +
 +  * http://stackoverflow.com/questions/3723316/what-is-causing-unable-to-allocate-memory-for-pool-in-php
 +  * http://www.cyberciti.biz/faq/linux-unix-php-warning-unable-to-allocate-memory-for-pool/
 +
 +==== (28)No space left on device: Couldn't create accept lock (/etc/httpd/logs/accept.lock) ====
 +
 +//Довольно редко встречающаяся ошибка, в основном связана с неосвобождением системой семафоров, которые выделяет для себя apache.//
 +
 +Решение
 +
 +<code># for i in `ipcs -s | awk '/httpd/ {print $2}'`; do (ipcrm -s $i); done</code>
 +
 +или так
 +
 +<code># ipcs -s | grep nobody | perl -e 'while (<STDIN>) { @a=split(/\s+/); print `ipcrm sem $a[1]`}'</code>
 +
 +Увеличить кол-во семафоров
 +
 +<file bash /etc/sysctl.conf>
 +kernel.msgmni = 1024
 +kernel.sem = 250 256000 32 1024
 +</file>
 +
 +Применить изменения
 +
 +<code># sysctl -p</code>
 +
 +http://artkiev.com/blog/error-no-space-left-on-device-couldnt-create-accept-lock.htm
 +
 +==== httpd dead but subsys locked ====
 +
 +https://klimchuk.wordpress.com/2015/09/08/httpd-dead-but-subsys-locked/
 +
 +См. выше Couldn't create accept lock
 +
 +==== Клон сайта ====
 +
 +У вас есть сайт и выделенный IP на сервере. У нехорошего человека есть домен и он направляет DNS на ваш IP. По чужому домену открывается ваш сайт. Вы теряете посетителей.
 +
 +FIXME
 +
 +<code>
 +RewriteBase /
 +RewriteCond %{HTTP_HOST} !^site.ru$ [NC]
 +RewriteRule ^(.*)$ http://site.ru/$1 [L,R=301]
 +</code>
 +
 +  * http://searchengines.guru/showthread.php?t=850530&page=4
 +  * http://security.stackexchange.com/questions/104481/cloned-site-with-tricky-http-host
 +
 +==== [authz_core:error]AH01630: client denied by server configuration ====
 +
 +http://httpd.apache.org/docs/2.4/upgrading.html#access
 +
 +//In 2.2, access control based on client hostname, IP address, and other characteristics of client requests was done using the directives Order, Allow, Deny, and Satisfy.//
 +
 +//In 2.4, such access control is done in the same way as other authorization checks, using the new module mod_authz_host.//
 +
 +Вместо
 +
 +<code>
 +Order allow,deny
 +Allow from all
 +</code>
 +
 +Теперь используется
 +
 +<code>Require all granted</code>
 +
 +Ещё немного примеров
 +
 +Было (2.2)
 +
 +<code>
 +order allow,deny
 +deny from 192.168.1.7
 +</code>
 +
 +Стало (2.4)
 +
 +<code>
 +Require all granted
 +Require not ip 192.168.1.7
 +</code>
 +
 +Было
 +
 +<code>
 +Order deny,allow
 +Deny from all
 +</code>
 +
 +Стало
 +
 +<code>Require all denied</code>
 +
 +==== Either all Options must start with + or -, or no Option may. ====
 +
 +Для всех опций надо добавлять +
 +
 +Правильно
 +
 +<code>Options +FollowSymLinks -Indexes</code>
 +
 +Неправильно
 +
 +<code>Options FollowSymLinks -Indexes</code>
 +
 +{{tag>apache httpd howto}}