Содержание

IIS

Для поддержки powershell:

import-module WebAdministration

IIS Advanced Logging

Расширенное логгирование IIS.
Позволяет создавать, настраивать свои поля в логе, фильтры, период ротации.

Работает с IIS 7, IIS 7.5, IIS 8

Скачать можно здесь, офф.сайт

X-Forwarded-For

Добавление X-Forwarded-For в лог IIS с помощью Advanced Logging и Enhanced Logging

Advanced Logging

  1. Устанавливаем Advanced Logging
  2. В IIS ManagerConnections - выбираем наш сервер
  3. На начальной странице заходим в Advanced Logging
  4. В правой панели Action
    1. Enable Advanced Logging
    2. Edit Logging FieldsAdd Field
      • Field ID: OriginalIP
      • Category: Default
      • Source type: Request Header
      • Source name: X-Forwarded-For
      • OK → OK
    3. Add Log Definition
      • Base file name: Client Original IP
      • Select Fields: …, OriginalIP
      • OK
    4. Apply

http://www.loadbalancer.org/blog/iis-and-x-forwarded-for-header

Enhanced Logging

Работает только на IIS 8.5 и выше

https://www.iis.net/learn/get-started/whats-new-in-iis-85/enhanced-logging-for-iis85

Добавить поле 'X-Forwarded-For' в лог файл:

Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST'  -filter "system.applicationHost/sites/siteDefaults/logFile/customFields" -name "." -value @{logFieldName='X-Forwarded-For';sourceName='X-Forwarded-For';sourceType='RequestHeader'}

https://techcommunity.microsoft.com/t5/iis-support-blog/how-to-use-x-forwarded-for-header-to-log-actual-client-ip/ba-p/873115

Добавление прав пользователю на службу

Чтобы разрешить локальному пользователю a.ivanov перезапускать службу, добавляем с помощью SubInACL (можно установить отдельно или в составе Resource Kits Tools) необходимые привилегии:

subinacl.exe /service w3svc /grant=COMPNAME-WS\a.ivanov=PTO

Привилегии:

F : Full Control
R : Generic Read
W : Generic Write
X : Generic eXecute
L : Read controL
Q : Query Service Configuration
S : Query Service Status
E : Enumerate Dependent Services
C : Service Change Configuration
T : Start Service
O : Stop Service
P : Pause/Continue Service
I : Interrogate Service 
U : Service User-Defined Control Commands

http://stackoverflow.com/questions/4436558/start-stop-a-windows-service-from-a-non-administrator-user-account

Содержимое директории

В нужной директории добавляем web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <directoryBrowse enabled="true" />
    </system.webServer>
</configuration>

Настройка

https://docs.hangfire.io/en/latest/deployment-to-production/making-aspnet-app-always-running.html

AppPool

%windir%\System32\inetsrv\config\applicationHost.config

startMode

ValueName
0OnDemand
1AlwaysRunning
$appPoolName = "MyWebPool"
Get-ItemProperty ("IIS:\AppPools\$appPoolName") -Name startMode.value
Set-ItemProperty ("IIS:\AppPools\$appPoolName") -Name startMode -value 1

idleTimeout

$appPoolName = "MyWebPool"
Get-ItemProperty ("IIS:\AppPools\$appPoolName") -Name processModel.idleTimeout.value
Set-ItemProperty ("IIS:\AppPools\$appPoolName") -Name processModel.idleTimeout -value ( [TimeSpan]::FromMinutes(0))

loadUserProfile

$appPoolName = "MyWebPool"
Get-ItemProperty ("IIS:\AppPools\$appPoolName") -Name ProcessModel.loadUserProfile.value
Set-ItemProperty ("IIS:\AppPools\$appPoolName") -Name ProcessModel.loadUserProfile -value False

Sites

Preload Enabled

$siteName = "MyWeb"
Set-WebConfigurationProperty -PSPath 'IIS:' -Filter "system.applicationHost/sites/site[@name='$siteName']/application" -Name "preloadEnabled" -Value "True"
Set-ItemProperty "IIS:\Sites\$siteName" -Name applicationDefaults.preloadEnabled -Value "True"

IIS SSL

https://www.nartac.com/Products/IISCrypto

Reverse Proxy

Необходимы 2 компонента:

Пример конфигурации с проксированием на тот же сайт по http исключая запросы начинающиеся на apk:

web.config

web.config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="ReverseProxyInboundRule1" stopProcessing="true">
                    <match url="^(?!apk)(.*)" />
                    <action type="Rewrite" url="http://{HTTP_HOST}/{R:1}" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>


Rewrite

Редирект всех запросов начинающихся на apk с HTTP на HTTPS:

web.config

web.config

    <system.webServer>
      <rewrite>
            <globalRules>
                <rule name="http_to_https_apk" stopProcessing="true">
                    <match url="^(apk.*)" />
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Temporary" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                </rule>
            </globalRules>
        </rewrite>
    </system.webServer>


Редирект всех запросов с HTTP на HTTPS исключая начинающихся на .well-known, исключая домен domain.loc, исключая клиентские ip (1.1.1.1, 1.0.0.1):

web.config

web.config

    <system.webServer>
        <rewrite>
            <globalRules>
                <rule name="redirect_to_https" enabled="true" stopProcessing="true">
                    <match url="^(?!.well-known)(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                        <add input="{HTTP_HOST}" matchType="Pattern" pattern="^domain.loc$" ignoreCase="true" negate="true" />
                        <add input="{REMOTE_ADDR}" pattern="^1.1.1.1$" negate="true" />
                        <add input="{REMOTE_ADDR}" pattern="^1.0.0.1$" negate="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Temporary" />
                </rule>
            </globalRules>
        </rewrite>
     </system.webServer>


web.config

Основной раздел:

<configuration>
  <system.webServer>
  </system.webServer>
</configuration>

Добавить mime тип:

    <staticContent>
      <mimeMap fileExtension=".onnx" mimeType="application/onnx-model" />
    </staticContent>

Добавить сжатие для mime типа:

    <httpCompression>
      <staticTypes>
        <add enabled="true" mimeType="application/onnx-model" />
      </staticTypes>
    </httpCompression>

https://learn.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap
https://learn.microsoft.com/en-us/iis/configuration/system.webserver/httpcompression/statictypes/add

Ошибки

Bad Request - Request Too Long
HTTP Error 400. The size of the request headers is too long.

Решение: Увеличить размер заголовка и размер строки запроса

New-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\HTTP\Parameters" -Name "MaxFieldLength" -Value 65536 -PropertyType "dword" -Force
New-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\HTTP\Parameters" -Name "MaxRequestBytes" -Value 131072 -PropertyType "dword" -Force

https://docs.microsoft.com/ru-RU/troubleshoot/iis/httpsys-registry-windows