Http error 400 the request hostname is invalid iis

When I try to hit my web app on port 8080 I get the following error Bad Request - Invalid Hostname HTTP Error 400. The request hostname is invalid. I don't even know where to begin to diagnos...

When I try to hit my web app on port 8080 I get the following error

Bad Request — Invalid Hostname
HTTP Error 400. The request hostname is invalid.

I don’t even know where to begin to diagnose this problem

MrWhite's user avatar

MrWhite

39.7k6 gold badges56 silver badges82 bronze badges

asked Jan 28, 2011 at 17:17

burnt1ce's user avatar

Did you check the binding is IIS? (inetmgr.exe) It may not be registered to accept all hostnames on 8080.

For example, if you set it up for mysite.com:8080 and hit it at localhost:8080, IIS will get the request but not have a hostname binding to match so it rejects.

Outside of that, you should check the IIS logs (C:inetpublogswmsvc#) on the server and see if you are seeing your request. Then you’ll know if its a problem on your client or on the server itself.

answered Jan 28, 2011 at 17:59

Taylor Bird's user avatar

Taylor BirdTaylor Bird

7,6771 gold badge24 silver badges31 bronze badges

2

FWIW, if you’d like to just allow requests directed to any hostname/ip then you can set your binding like so:

<binding protocol="http" bindingInformation="*:80:*" />

I use this binding so that I can load a VM with IE6 and then debug my application.


EDIT: While using IIS Express to debug, the default location for this option’s config file is

C:Users{User}DocumentsIISExpressconfigapplicationhost.config

StaRbUck42's user avatar

answered Sep 26, 2013 at 15:11

Jeff LaFay's user avatar

Jeff LaFayJeff LaFay

12.7k13 gold badges72 silver badges100 bronze badges

2

This page by Microsoft describes how to set up access to IIS Server Express from other computers on the local network.

In a nutshell:

1) from a command prompt with admin privileges:

netsh http add urlacl url=http://[your ip address]:8181/ user=everyone

2) In Windows Firewall with Advanced Security, create a new inbound rule for port 8181 to allow external connections

3) In applicationhost.config, in the node for your project, add:

<binding protocol="http" bindingInformation="*:8181:[your ip address]" />

Do NOT add (as was suggested in another answer):

<binding protocol="http" bindingInformation="*:8181:*" />

The above wildcard binding broke my access from http://192.168.1.6:8181/

itzmebibin's user avatar

itzmebibin

9,0808 gold badges48 silver badges61 bronze badges

answered Oct 29, 2014 at 22:44

Erwin's user avatar

ErwinErwin

5356 silver badges8 bronze badges

3

So, I solved this by going to my website in IIS Manager and changing the host name in site bindings from localhost to *. Started working immediately.

Site Bindings in IIS

answered Aug 10, 2015 at 17:00

SINGULARITY's user avatar

SINGULARITYSINGULARITY

1,08711 silver badges11 bronze badges

3

If working on local server or you haven’t got domain name, delete «Host Name:» field.
enter image description here

answered Apr 29, 2020 at 14:31

Tahir FEYZIOGLU's user avatar

Don’t forget to bind to the IPv6 address as well! I was trying to add a site on 127.0.0.1 using localhost and got the bad request/invalid hostname error. When I pinged localhost it resolved to ::1 since IPv6 was enabled so I just had to add the additional binding to fix the issue.

IIS Site Bindings

answered Oct 30, 2015 at 21:45

Jeff Camera's user avatar

Jeff CameraJeff Camera

5,2645 gold badges42 silver badges59 bronze badges

1

This solved my problem (sorry for my bad English):

  1. open cmd as administrator and run command (Without the square brackets):
    netsh http add urlacl url=http://[ip adress]:[port]/ user=everyone

  2. in documents/iisexpress/config/applicationhost.config and in your root project folder in (hidden) folder: .vs/config/applicationhost.config you need add row to «site» tag:
    <binding protocol="http" bindingInformation="*:8080:192.xxx.xxx.xxx" />

  3. open «internet information services (iis) manager»
    (to find it: in search in taskbar write «Turn Window features on or off» and open result and then check the checkbox «internet information service» and install that):

    1. in left screen click: computer-name —> Sites —> Default Web Site and
    2. then click in right screen «Binding»
    3. click Add button
    4. write what you need and press «OK».
  4. open «Windows Firewall With Advanced Security»,

    1. in left screen press «Inbound Rules» and then
    2. press in right screen «New Rule…»
    3. check port and press Next,
    4. check TCP and your port and press Next,
    5. check «Allow the connection» and press Next,
    6. check all checkbox and press Next,
    7. write name and press Finish.
  5. done.

Yahoo Serious's user avatar

answered Jul 12, 2017 at 22:05

izik f's user avatar

izik fizik f

2,2792 gold badges16 silver badges16 bronze badges

I’m not sure if this was your problem but for anyone that’s trying to access his web application from his machine and having this problem:

Make sure you’re connecting to 127.0.0.1 (a.k.a localhost) and not to your external IP address.

Your URL should be something like http://localhost:8181/ or http://127.0.0.1:8181 and not http://YourExternalIPaddress:8181/.


Additional information:
The reason this works is because your firewall may block your own request. It can be a firewall on your OS and it can be (the usual) your router.

When you connect to your external IP address, you connect to you from the internet, as if you were a stranger (or a hacker).
However when you connect to your localhost, you connect locally as yourself and the block is obviously not needed (& avoided altogether).

answered Jan 26, 2013 at 9:26

MasterMastic's user avatar

MasterMasticMasterMastic

20.5k11 gold badges67 silver badges90 bronze badges

6

You can use Visual Studio 2005/2008/2010 CMD tool. Run it as admin, and write

aspnet_regiis -i

At last I can run my app successfully.

phant0m's user avatar

phant0m

16.4k5 gold badges49 silver badges81 bronze badges

answered Jul 28, 2012 at 4:13

FrankFan's user avatar

I also had this issue, but it was related to AllowedHosts of my application configuration

If it’s a .Net application you should probably have appsettings.json
Have a look of it’s AllowedHosts and try to change it to all-allowed «*»

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*",
}

So in case of incorrect AllowedHosts value, you will also have BarRequest error

answered Jan 17, 2022 at 16:07

Anton Nikitsiuk's user avatar

1

Check your local hosts file (C:WindowsSystem32driversetchosts for example). In my case I had previously used this to point a URL to a dev box and then forgotten about it. When I then reused the same URL I kept getting Bad Request (Invalid Hostname) because the traffic was going to the wrong server.

answered Jul 25, 2013 at 13:31

robaker's user avatar

robakerrobaker

1,0287 silver badges11 bronze badges

I got this error when I tried to call a webservice using «localhost». I fixed it by using the actual IP instead (192.168…)

answered Jun 25, 2014 at 14:42

Cosmin's user avatar

CosminCosmin

2,3372 gold badges23 silver badges28 bronze badges

1

I saw the same error after using msdeploy to copy the application to a new server. It turned out that the bindings were still using the IP address from the previous server. So, double check IP address in the IIS bindings. (Seems obvious after the fact, but did not immediately occur to me to check it).

answered Jun 3, 2015 at 20:49

dan9298's user avatar

dan9298dan9298

1951 silver badge11 bronze badges

Double check the exact URL you’re providing.
I saw this error when I missed off the route prefix defined in ASP.NET so it didn’t know where to route the request.

answered Sep 14, 2018 at 14:29

Taran's user avatar

TaranTaran

11.9k3 gold badges39 silver badges46 bronze badges

Make sure IIS is listening to your port.

In my case this was the issue. So I had to change my port to something else like 8083 and it solved this issue.

answered Sep 23, 2019 at 11:26

Dudi's user avatar

DudiDudi

3,0291 gold badge25 silver badges23 bronze badges

  • Remove From My Forums
  • Question

  • User1152153909 posted

     Hi,

     All I’m trying to do is create a simple website. To begin with. Nothing fancy, so all the fancy stuff I’ll leave toll later. I’ve gone through three different versions of «setting up a simple website. None of them have worked for me. I am looking for
    an even simpler, step by step guide with examples on how to set up a simple, stupid website.

     And I thought Apache was supposed to be complicated! When I use the default site, I get the splash page no problem. When I try to serve my contect on a «new site» with the same IP and turn off the default website, I get the subject line error.

     I’ve been working on getting this danged thing set up for almost a month now. I’d appreciate any help you can offer in a simple, step by step mode. I don’t need fancy, like I said. Nor a smart aleck. Just someone who’s willing to hold my hand through
    the first setup.

     The frustration level here is intense.

    Thanks!

    Blaine 

Answers

  • User-2064283741 posted

    Ok. Then there seems to be something in your configuartion of the site you setup.

    The easist way might be to place your applciation/site under the default website liek I sugegsted before.

    So stop the current one. Place you code under where the folder/directory of the default site and try and browser directly to a page.

    • Marked as answer by

      Tuesday, September 28, 2021 12:00 AM

01

«Допустим, что вы, не устояв перед натиском прогресса, установили Visual Studio 2013 и перенесли в неё существующий проект, который содержит поддомены типа part.mysite.com. После запуска проекта вас будет ждать разочарование — на любую страницу страницу с поддоменом сервер отреагирует досадной ошибкой:

02

Bad Request — Invalid Hostname.
HTTP Error 400. The request hostname is invalid.

03

Первым делом вы конечно же кинитесь проверять ваш файл hosts (C:WindowsSystem32driversetc), но с удивлением обнаружите, что с ним все в порядке…»

04

Похоже на страшилку. Все дело в том, что в Visual Studio 2013 по умолчанию встроен сервер IIS Express. У него немного иной механизм взаимодействия с адресами. Визуальной среды настройки он не имеет, поэтому все взаимодействие происходит через командную строку. Также для конфигурирования IIS Express используется файл applicationhost.config, располагающийся в папке %UserName%DocumentsIISExpressconfig. Открываем его в студийном редакторе и находим раздел отвечающий за проект:

05 XML

1
2
3
4
5
6
7
8

<site name=«MVC_speckm.ru_v1.0» id=«3»>
<application path=«/» applicationPool=«Clr4IntegratedAppPool»>
<virtualDirectory path=«/» physicalPath=«Путь_к_вашему_проекту» />
</application>
<bindings>

<binding protocol=«http» bindingInformation=«*:54524:localhost» />

</bindings>
</site>

06

Чтобы сервер пропускал любой адрес с этим портом, заменяем выделенную строку на:

07 XML

1

<binding protocol=«http» bindingInformation=«*:54524:*» />

08

Либо если вы хотите обращаться к своему проекту по осмысленному адресу, то, например:

09 XML

1

<binding protocol=«http» bindingInformation=«*:54524:debug.codius.ru» />

10

Далее отключаем IIS Express, запускаем под администратором командную строку и вводим команду резервирования url-адреса (порт указываем свой):

11

netsh http add urlacl url=http://*:54524/ user=everyone

12

В ответ на выполнение этой команды вы (если у вас не англоязычный Windows) конечно же получите ошибку Сбой создания SDDL. Ошибка: 1332. Параметр задан неверно, потому что нет такого пользователя в русскоязычном Windows — зато есть пользователь Все:

13

netsh http add urlacl url=http://*:54524/ user=Все

14

Снова запускаем проект. Готово!

15 На заметку:

Не забываем вносить, при необходимости, изменения в файл hosts:
# localhost name resolution is handled within DNS itself.
127.0.0.1 localhost
127.0.0.1 debug.codius.ru
# ::1 localhost

17

Похожие запросы:

  • Using Custom Domains With IIS Express
  • Сбой создания SDDL. Ошибка: 1332. Параметр задан неверно
  • Bad Request — Invalid Hostname IIS7
  • HTTP Error 400. The request hostname is invalid
  • IIS Express – Error 400
  • Bad Request — Invalid Hostname
  • ASP.NET — Как создать поддомен в IIS?
  • Что это значит?? Bad Request (Invalid Hostname)
  • Bad Request — Invalid Hostname while connect to localhost

IIS 8.5

Развлекался тут собственно
На сервере Windows 2012 развернул сайт, а он мне

Bad Request — Invalid Hostname


HTTP Error 400. The request hostname is invalid.

причем по барабану localhost в адресной строке или IP-адрес.

Оказалось в привязках к вебсайту нужно оставлять незаполненным значение «Имя узла»

и даже брандмауэр настраивать не надо

[16.12.2014]
Собственно перешел с XML на БД естественно MS SQL Express 2014 (в данное время я люблю Microsoft — после Oracle (и не из-за баз последнего)). На локальном компе все хорошо: сайт отображается. Закидываю на сервер — ошибка:

[Win32Exception (0x80004005): Не удается найти указанный файл]

[SqlException (0x80131904): При установлении соединения с SQL Server произошла ошибка, связанная с сетью или с определенным экземпляром. Сервер не найден или недоступен. Убедитесь, что имя экземпляра указано правильно и что на SQL Server разрешены удаленные соединения. (provider: SQL Network Interfaces, error: 52 — Не найден компонент Local Database Runtime. Проверьте, что сервер SQL Server Express правильно установлен и использование компонента Local Database Runtime включено.)]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6564850
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +815

…ну и так далее

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

IIS APPPOOLDefaultAppPool

Однако это не помогло.
Оказывается нужно было ConnectionString поменять с
connectionString=»Data Source=(LocalDB)v11.0;AttachDbFilename=|DataDirectory|MainDB.mdf;Integrated Security=True;Connect Timeout=30″ providerName=»System.Data.SqlClient»

на

connectionString=»Data Source=.SQLEXPRESS;AttachDbFileName=|DataDirectory|MainDB.mdf;Integrated Security=True;User Instance=True;Connect Timeout=30″ providerName=»System.Data.SqlClient»

Барахолка в Железнодорожном

Лучший поставщик комплектующих

20190103232617

Bad Request — Invalid Hostname
HTTP Error 400. The request hostname is invalid.
How to debug AspNetCoreSubdomain locally? I setup step by step reffer to https://github.com/mariuszkerl/AspNetCoreSubdomain/wiki/Debugging-subdomains-locally

AspNetCoreSubdomain-1.1.0AspNetCoreSubdomain-1.1.0src.vsconfig

      <site name="WebSite1" id="1" serverAutoStart="true">
        <application path="/">
          <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%WebSite1" />
        </application>
        <bindings>
          <binding protocol="http" bindingInformation=":8080:localhost" />
        </bindings>
      </site>
      <site name="AspNetCoreSubdomain.Samples" id="2">
        <application path="/" applicationPool="Clr4IntegratedAppPool">
          <virtualDirectory path="/" physicalPath="C:UsersTaoDownloadsAspNetCoreSubdomain-1.1.0AspNetCoreSubdomain-1.1.0srcAspNetCoreSubdomain.Samples" />
        </application>
        <bindings>
          <binding protocol="http" bindingInformation="*:54575:localhost" />
          <binding protocol="http" bindingInformation="*:54575:mycompany.localhost" />
          <binding protocol="http" bindingInformation="*:54575:subdomain1.localhost" />
          <binding protocol="http" bindingInformation="*:54575:subdomain2.localhost" />
          <binding protocol="http" bindingInformation="*:54575:subdomain3.localhost" />
          <binding protocol="http" bindingInformation="*:54575:home.localhost" />
          <binding protocol="http" bindingInformation="*:54575:test.localhost" />
          <binding protocol="http" bindingInformation="*:54575:subdomains.page.localhost" />
          <binding protocol="http" bindingInformation="*:54575:subdomain.forms.page.localhost" />
        </bindings>
      </site>

C:WindowsSystem32driversetchosts

To be able to debug subdomains locally

127.0.0.1   subdomain1.localhost
127.0.0.1   subdomain2.localhost
127.0.0.1   subdomain3.localhost
127.0.0.1   home.localhost
127.0.0.1   test.localhost
127.0.0.1	staticsubdomain1.localhost
127.0.0.1	staticsubdomain2.localhost
127.0.0.1	subdomains.page.localhost
127.0.0.1	subdomain.forms.page.localhost
127.0.0.1       mycompany.localhost

C:UsersTao>ping staticsubdomain1.localhost

正在 Ping staticsubdomain1.localhost [127.0.0.1] 具有 32 字节的数据:
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=64
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=64
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=64
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=64

127.0.0.1 的 Ping 统计信息:
数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 0ms,最长 = 0ms,平均 = 0ms

C:UsersTao>

Понравилась статья? Поделить с друзьями:
  • Http error 400 a request header field is too long
  • Http error 334
  • Http error 308
  • Http error 307
  • Http error 304 not modified