Ошибка при отправке запроса http к https

Форум КриптоПро
 » 
КриптоПро УЦ
 » 
КриптоПро УЦ 2.0
 » 
Восстановление работоспособности УЦ 2.0


Offline

vadjunik

 


#11
Оставлено
:

8 ноября 2021 г. 12:47:14(UTC)

vadjunik

Статус: Активный участник

Группы: Участники

Зарегистрирован: 09.12.2016(UTC)
Сообщений: 127
Мужчина
Российская Федерация
Откуда: Таганрог

Сказал «Спасибо»: 15 раз

Автор: Захар Тихонов Перейти к цитате

а точно эта учетка у ЦР (посмотреть можно перейдя на вкладку Центры регистрации)?

Не понял, о какой вкладке речь? ( Где конкретно глянуть — можно скрин со стрелкой?

Про это?

UserPostedImage

Действительно, не тот акаунт был выбран и прав у него не было. Установил, но разницы нет.

UserPostedImage

Перезапустить все сервисы?

Отредактировано пользователем 8 ноября 2021 г. 13:09:09(UTC)
 | Причина: Добавил параметры акаунта


Вверх


Offline

Захар Тихонов

 


#12
Оставлено
:

8 ноября 2021 г. 13:20:48(UTC)

Захар Тихонов

Статус: Сотрудник

Группы: Участники

Зарегистрирован: 17.08.2015(UTC)
Сообщений: 3,083
Мужчина
Тонга
Откуда: Калининград

Сказал «Спасибо»: 38 раз
Поблагодарили: 553 раз в 530 постах

Да, можно посмотреть учетку если не выбрать ваш ЦР, а кликнув на Центры Регистрации (чуть выше)

Да, перезапустите IIS и проверьте связь (Ping-CA с отключенным прокси). Или весь сервер, если есть возможность.

Техническую поддержку оказываем тут.
Наша база знаний.


Вверх


Offline

vadjunik

 


#13
Оставлено
:

8 ноября 2021 г. 15:12:31(UTC)

vadjunik

Статус: Активный участник

Группы: Участники

Зарегистрирован: 09.12.2016(UTC)
Сообщений: 127
Мужчина
Российская Федерация
Откуда: Таганрог

Сказал «Спасибо»: 15 раз

Автор: Захар Тихонов Перейти к цитате

Да, можно посмотреть учетку если не выбрать ваш ЦР, а кликнув на Центры Регистрации (чуть выше)

Угу, с системным акаунтом понятно.

Автор: Захар Тихонов Перейти к цитате

Да, перезапустите IIS и проверьте связь (Ping-CA с отключенным прокси). Или весь сервер, если есть возможность.

Картина поменялась (но идентична, что с активированным прокси, что без него):

Код:

PS C:> Ping-CA -AuthorityName "Пробный корневой УЦ 2012 (512)"
Ping-CA : Ошибка соединения с центром сертификации Пробный корневой УЦ 2012 (512).
Ошибка при отправке запроса HTTP к https://ib-crypto1/ca/CertRequestService.svc/. Возможно, это вызвано тем, что сертификат сервера не сконфигур
ирован с HTTP.SYS для случая HTTPS. Это может быть также вызвано несоответствием привязки безопасности между клиентом и сервером.
Базовое соединение закрыто: Непредвиденная ошибка при передаче.
Не удается прочитать данные из транспортного соединения: Удаленный хост принудительно разорвал существующее подключение.
Удаленный хост принудительно разорвал существующее подключение
At line:1 char:1
+ Ping-CA -AuthorityName "Пробный корневой УЦ 2012 (512)"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Ping-CA], InvalidOperationException
    + FullyQualifiedErrorId : UnhandledError,RegistrationService.Commands.PingCACommand

Сертификат для HTTPS — валидный.
Сам комп не перезапускал — только службы ИИС и ЦС (ЦС, ЦР и службу управления ключами). Стоит все же перезапустить и комп?

Отредактировано пользователем 8 ноября 2021 г. 15:15:49(UTC)
 | Причина: Не указана


Вверх


Offline

Захар Тихонов

 


#14
Оставлено
:

8 ноября 2021 г. 16:06:30(UTC)

Захар Тихонов

Статус: Сотрудник

Группы: Участники

Зарегистрирован: 17.08.2015(UTC)
Сообщений: 3,083
Мужчина
Тонга
Откуда: Калининград

Сказал «Спасибо»: 38 раз
Поблагодарили: 553 раз в 530 постах

Вы в прошлый раз не приложили веб сертификат. Приложите его сейчас.
А также, выпустите внеочередные CRL.

Техническую поддержку оказываем тут.
Наша база знаний.


Вверх


Offline

vadjunik

 


#15
Оставлено
:

8 ноября 2021 г. 17:20:07(UTC)

vadjunik

Статус: Активный участник

Группы: Участники

Зарегистрирован: 09.12.2016(UTC)
Сообщений: 127
Мужчина
Российская Федерация
Откуда: Таганрог

Сказал «Спасибо»: 15 раз

Автор: Захар Тихонов Перейти к цитате

Вы в прошлый раз не приложили веб сертификат. Приложите его сейчас.

Веб-сертификат? В 7-м посту же, внизу, вот еще раз https://yadi.sk/d/xvCCL4e6y1DQ0w.

Автор: Захар Тихонов Перейти к цитате

А также, выпустите внеочередные CRL.

UserPostedImage

Упс… такой вот облом (

Отредактировано пользователем 8 ноября 2021 г. 17:32:09(UTC)
 | Причина: Не указана


Вверх


Offline

Захар Тихонов

 


#16
Оставлено
:

9 ноября 2021 г. 9:45:03(UTC)

Захар Тихонов

Статус: Сотрудник

Группы: Участники

Зарегистрирован: 17.08.2015(UTC)
Сообщений: 3,083
Мужчина
Тонга
Откуда: Калининград

Сказал «Спасибо»: 38 раз
Поблагодарили: 553 раз в 530 постах

Автор: vadjunik Перейти к цитате

Автор: Захар Тихонов Перейти к цитате

Вы в прошлый раз не приложили веб сертификат. Приложите его сейчас.

Веб-сертификат? В 7-м посту же, внизу, вот еще раз https://yadi.sk/d/xvCCL4e6y1DQ0w.

Клиентский сертификат ЦР — это не веб сертификат. У вас даже имя у файла «Сертификат аутентификации ЦР».

Автор: vadjunik Перейти к цитате

UserPostedImage
Упс… такой вот облом (

Загрузите в ‘агенте управления ключами’ ключи и проверьте выпуск CRL.

Техническую поддержку оказываем тут.
Наша база знаний.


Вверх


Offline

vadjunik

 


#17
Оставлено
:

9 ноября 2021 г. 10:26:24(UTC)

vadjunik

Статус: Активный участник

Группы: Участники

Зарегистрирован: 09.12.2016(UTC)
Сообщений: 127
Мужчина
Российская Федерация
Откуда: Таганрог

Сказал «Спасибо»: 15 раз

Автор: Захар Тихонов Перейти к цитате

Клиентский сертификат ЦР — это не веб сертификат. У вас даже имя у файла «Сертификат аутентификации ЦР».

Не допонял про какой сертификат речь (( Вот серт используемый для подключения к ЦР из «Консоли ЦР» https://yadi.sk/d/_VEnc7pcy4GxKA или речь про какой?

Автор: Захар Тихонов Перейти к цитате

Загрузите в ‘агенте управления ключами’ ключи и проверьте выпуск CRL.

С ключами какая-то проблема имеет место быть ( Почему-то отвалился ключ «Цезарева» для выпуска сертификатов — а был! Отломал что-то ((

UserPostedImage

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

UserPostedImage

Лог ошибки при попытке подключения к ЦР из консоли:

Код:

При запросе политики с ЦС получено исключение.
System.ServiceModel.CommunicationException: Ошибка при отправке запроса HTTP к https://ib-crypto1/ca/CertRequestService.svc/. Возможно, это вызвано тем, что сертификат сервера не сконфигурирован с HTTP.SYS для случая HTTPS. Это может быть также вызвано несоответствием привязки безопасности между клиентом и сервером. ---> System.Net.WebException: Базовое соединение закрыто: Непредвиденная ошибка при передаче. ---> System.IO.IOException: Не удается прочитать данные из транспортного соединения: Удаленный хост принудительно разорвал существующее подключение. ---> System.Net.Sockets.SocketException: Удаленный хост принудительно разорвал существующее подключение
   в System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- Конец трассировки внутреннего стека исключений ---
   в System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   в System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
   в System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   в System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   в System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
   в System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
   в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   в System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
   в System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   в System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   в System.Net.ConnectStream.WriteHeaders(Boolean async)
   --- Конец трассировки внутреннего стека исключений ---
   в System.Net.HttpWebRequest.GetResponse()
   в System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   --- Конец трассировки внутреннего стека исключений ---

Server stack trace: 
   в System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   в System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   в System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   в System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   в System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   в System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   в RegistrationService.BusinessLogic.ProcessClient.Wait(Queue queue, Conversation conversation, TimeSpan timeout)
   в RegistrationService.BusinessLogic.ProcessClient.WaitComplete(TimeSpan timeout)
   в RegistrationService.RegSrv.PolicyUpdateTask.Execute(IScriptContext`1 context)

Вверх


Offline

Захар Тихонов

 


#18
Оставлено
:

9 ноября 2021 г. 10:35:19(UTC)

Захар Тихонов

Статус: Сотрудник

Группы: Участники

Зарегистрирован: 17.08.2015(UTC)
Сообщений: 3,083
Мужчина
Тонга
Откуда: Калининград

Сказал «Спасибо»: 38 раз
Поблагодарили: 553 раз в 530 постах

Автор: vadjunik Перейти к цитате

или речь про какой?

вот этот 1.png (574kb) загружен 3 раз(а).

Автор: Захар Тихонов Перейти к цитате

С ключами какая-то проблема имеет место быть ( Почему-то отвалился ключ «Цезарева» для выпуска сертификатов — а был! Отломал что-то ((
UserPostedImage

А что с ключами которые не загружены, истекли? Если да, то выведите их из эксплуатации.

Техническую поддержку оказываем тут.
Наша база знаний.


Вверх


Offline

vadjunik

 


#19
Оставлено
:

9 ноября 2021 г. 12:58:35(UTC)

vadjunik

Статус: Активный участник

Группы: Участники

Зарегистрирован: 09.12.2016(UTC)
Сообщений: 127
Мужчина
Российская Федерация
Откуда: Таганрог

Сказал «Спасибо»: 15 раз

Автор: Захар Тихонов Перейти к цитате

Автор: vadjunik Перейти к цитате

или речь про какой?

вот этот 1.png (574kb) загружен 3 раз(а).

https://yadi.sk/d/S-vHswOHLqhovg

Автор: Захар Тихонов Перейти к цитате

А что с ключами которые не загружены, истекли? Если да, то выведите их из эксплуатации.

Как это узнать? Так понимаю, через консоль ЦС, подскажите в каком доке описано?

«Недоступные» ключи, я так понимаю, уже никак нельзя «вывести из эксплуатации». Потому и думаю в последствии грохнуть «левых» админов ЦС.
UserPostedImage

Для Цезарева (https://yadi.sk/d/Nt56pTBEll9SJw пароль на контейнер 123) точно не истек, ибо я выпускал сертификат на днях (как начал этой проблемой заниматься). Остальные — артефакты прошлых времен, планирую зачистить после того, как восстановлю работоспособность комплекса.

Отредактировано пользователем 9 ноября 2021 г. 13:03:03(UTC)
 | Причина: Не указана


Вверх


Offline

Захар Тихонов

 


#20
Оставлено
:

9 ноября 2021 г. 13:43:01(UTC)

Захар Тихонов

Статус: Сотрудник

Группы: Участники

Зарегистрирован: 17.08.2015(UTC)
Сообщений: 3,083
Мужчина
Тонга
Откуда: Калининград

Сказал «Спасибо»: 38 раз
Поблагодарили: 553 раз в 530 постах

Любой ключ можно вывести из эксплуатации. С права есть этот пункт в Диспетчере УЦ, после выделения любого ключа ЦС.

Укажите установленную версию КриптоПро CSP.
Пришлите вывод Get-CAReference

Техническую поддержку оказываем тут.
Наша база знаний.


Вверх

Пользователи, просматривающие эту тему

Guest

Форум КриптоПро
 » 
КриптоПро УЦ
 » 
КриптоПро УЦ 2.0
 » 
Восстановление работоспособности УЦ 2.0

Быстрый переход
 

Вы не можете создавать новые темы в этом форуме.

Вы не можете отвечать в этом форуме.

Вы не можете удалять Ваши сообщения в этом форуме.

Вы не можете редактировать Ваши сообщения в этом форуме.

Вы не можете создавать опросы в этом форуме.

Вы не можете голосовать в этом форуме.

I’m running a Sinatra app behind passenger/nginx. I’m trying to get it to respond to both http and https calls. The problem is, when both are defined in the server block https calls are responded to normally but http yields a 400 «The plain HTTP request was sent to HTTPS port» error. This is for a static page so I’m guessing Sinatra has nothing to do with this. Any ideas on how to fix this?

Here’s the server block:

server {
        listen 80;
        listen 443  ssl;
        server_name localhost;
        root /home/myhome/app/public;
        passenger_enabled on;

        ssl on;
        ssl_certificate      /opt/nginx/ssl_keys/ssl.crt;
        ssl_certificate_key  /opt/nginx/ssl_keys/ssl.key;
        ssl_protocols        SSLv3 TLSv1;
        ssl_ciphers          HIGH:!aNULL:!MD5;

        location /static {
            root  /home/myhome/app/public;
            index  index.html index.htm index.php;
        }

        error_page 404 /404.html;

        # redirect server error pages to the static page /50x.html
        error_page 500 /500.html;

        access_log /home/myhome/app/logs/access.log;
        error_log /home/myhome/app/logs/error.log;
}

asked Jan 7, 2012 at 10:21

Johnny's user avatar

2

I ran into a similar problem. It works on one server and does not on another server with same Nginx configuration. Found the the solution which is answered by Igor here http://forum.nginx.org/read.php?2,1612,1627#msg-1627

Yes. Or you may combine SSL/non-SSL servers in one server:

server {
  listen 80;
  listen 443 default ssl;

  # ssl on   - remember to comment this out

}

Niyaz's user avatar

Niyaz

53.7k55 gold badges150 silver badges182 bronze badges

answered Jan 10, 2012 at 22:53

bobojam's user avatar

bobojambobojam

2,4251 gold badge15 silver badges7 bronze badges

8

The above answers are incorrect in that most over-ride the ‘is this connection HTTPS’ test to allow serving the pages over http irrespective of connection security.

The secure answer using an error-page on an NGINX specific http 4xx error code to redirect the client to retry the same request to https. (as outlined here https://serverfault.com/questions/338700/redirect-http-mydomain-com12345-to-https-mydomain-com12345-in-nginx )

The OP should use:

server {
  listen        12345;
  server_name   php.myadmin.com;

  root         /var/www/php;

  ssl           on;

  # If they come here using HTTP, bounce them to the correct scheme
  error_page 497 https://$server_name:$server_port$request_uri;

  [....]
}

kaiser's user avatar

kaiser

21.7k16 gold badges87 silver badges109 bronze badges

answered Sep 26, 2012 at 21:04

Michael J. Evans's user avatar

3

The error says it all actually. Your configuration tells Nginx to listen on port 80 (HTTP) and use SSL. When you point your browser to http://localhost, it tries to connect via HTTP. Since Nginx expects SSL, it complains with the error.

The workaround is very simple. You need two server sections:

server {
  listen 80;

  // other directives...
}

server {
  listen 443;

  ssl on;
  // SSL directives...

  // other directives...
}

answered Jan 7, 2012 at 16:36

Alexander Azarov's user avatar

Alexander AzarovAlexander Azarov

12.9k2 gold badges50 silver badges54 bronze badges

1

According to wikipedia article on status codes. Nginx has a custom error code when http traffic is sent to https port(error code 497)

And according to nginx docs on error_page, you can define a URI that will be shown for a specific error.
Thus we can create a uri that clients will be sent to when error code 497 is raised.

nginx.conf

#lets assume your IP address is 89.89.89.89 and also 
#that you want nginx to listen on port 7000 and your app is running on port 3000

server {
    listen 7000 ssl;
 
    ssl_certificate /path/to/ssl_certificate.cer;
    ssl_certificate_key /path/to/ssl_certificate_key.key;
    ssl_client_certificate /path/to/ssl_client_certificate.cer;

    error_page 497 301 =307 https://89.89.89.89:7000$request_uri;

    location / {
        proxy_pass http://89.89.89.89:3000/;

        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Protocol $scheme;
    }
}

However if a client makes a request via any other method except a GET, that request will be turned into a GET. Thus to preserve the request method that the client came in via; we use error processing redirects as shown in nginx docs on error_page

And thats why we use the 301 =307 redirect.

Using the nginx.conf file shown here, we are able to have http and https listen in on the same port

Community's user avatar

answered Feb 4, 2015 at 13:56

Komu's user avatar

KomuKomu

14k2 gold badges28 silver badges22 bronze badges

2

I had the exact same issue, I have kind of the same configuration as your exemple and I got it working by removing the line :

ssl on;

To quote the doc:

If HTTP and HTTPS servers are equal, a single server that handles both HTTP and HTTPS requests may be configured by deleting the directive “ssl on” and adding the ssl parameter for *:443 port

answered Nov 22, 2012 at 16:33

Remiz's user avatar

RemizRemiz

3903 silver badges10 bronze badges

1

Here is an example to config HTTP and HTTPS in same config block with ipv6 support. The config is tested in Ubuntu Server and NGINX/1.4.6 but this should work with all servers.

server {
    # support http and ipv6
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    # support https and ipv6
    listen 443 default_server ssl;
    listen [::]:443 ipv6only=on default_server ssl;

    # path to web directory
    root /path/to/example.com;
    index index.html index.htm;

    # domain or subdomain
    server_name example.com www.example.com;

    # ssl certificate
    ssl_certificate /path/to/certs/example_com-bundle.crt;
    ssl_certificate_key /path/to/certs/example_com.key;

    ssl_session_timeout 5m;

    ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
    ssl_prefer_server_ciphers on;
}

Don’t include ssl on which may cause 400 error. The config above should work for

http://example.com

http://www.example.com

https://example.com

https://www.example.com

Hope this helps!

answered Jan 1, 2016 at 4:32

Madan Sapkota's user avatar

Madan SapkotaMadan Sapkota

24.9k11 gold badges113 silver badges117 bronze badges

if use phpmyadmin add: fastcgi_param HTTPS on;

answered Mar 31, 2012 at 0:11

Rodrigo Gregorio's user avatar

Actually you can do this with:

ssl off; 

This solved my problem in using nginxvhosts; now I am able to use both SSL and plain HTTP.
Works even with combined ports.

Brad Koch's user avatar

Brad Koch

19k19 gold badges107 silver badges137 bronze badges

answered Feb 20, 2012 at 17:02

rapan iosif's user avatar

1

its error 497 and not error 400 . you can handle Error 497 like this and redirect http to https with a 301 (moved permanently) or 302 (moved temporary) like this:

error_page 497 = @foobar;

location @foobar {
return 301 https://$host:$server_port$request_uri;
}

this will redirect you to the exact url you requested but replace your request ‘http’ with ‘https’ with no error or confirm (its 301 redirect and counts as seo safe)

answered Aug 15, 2021 at 14:08

Alireza Far's user avatar

In my case my response redirected from jenkins to 443

Just added a proxy redirect in nginx configuration to make it work

proxy_redirect http://test.example.com:443/ https://test.example.com/;

answered Sep 22, 2021 at 16:59

Ishan's user avatar

IshanIshan

6701 gold badge8 silver badges19 bronze badges

In my case just those lines help me:

   if ($scheme = 'http') {
        return 301 https://$server_name$request_uri;
    }

answered Jan 16 at 8:14

Ivan's user avatar

IvanIvan

311 silver badge5 bronze badges

1

In this article, we will show how to solve the “400 Bad Request: The plain HTTP request was sent to HTTPS port” in Nginx HTTP server. This error normally arises when you try to configure Nginx to handle both HTTP and HTTPS requests.

For the purpose of this guide, we are considering a scenario in which nginx is serving multiple websites implemented through server blocks (or virtual hosts in Apache) only one website uses SSL and the rest do not.

Read Also: The Ultimate Guide to Secure, Harden and Improve Performance of Nginx

We will also consider the sample SSL configuration below (we have changed the actual domain name for security reasons), which tells nginx to listen to both port 80 and 443. And all requests on HTTP should to be redirected to HTTPS by default.

Nginx Sample Configuration

server{
        listen 80;
        server_name example.com www.example.com;
        return 301 https://www.example.com$request_uri;
}
server {
        listen 443 ssl http2;
        server_name example.com www.example.com;

        root   /var/www/html/example.com/;
        index index.php index.html index.htm;

        #charset koi8-r;
        access_log /var/log/nginx/example.com/example.com_access_log;
        error_log   /var/log/nginx/example.com/example.com_error_log   error;

        # SSL/TLS configs
        ssl on;
        ssl_certificate /etc/ssl/certs/example_com_cert_chain.crt;
        ssl_certificate_key /etc/ssl/private/example_com.key;

        include /etc/nginx/ssl.d/ssl.conf;

        location / {
                try_files $uri $uri/ /index.php?$query_string;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
                root   /var/www/html/example.com/;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ .php$ {

                root   /var/www/html/example.com/;
                fastcgi_pass   127.0.0.1:9001;
                #fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include         fastcgi_params;
                include /etc/nginx/fastcgi_params;

        }
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /.ht {
        #    deny  all;
        #}
}

Using the above configuration, once a client tries to access your site via port 80 i.e http://example.com, the error in question will be displayed as in the following screen shot.

Nginx 404 Bad Request Error

Nginx 404 Bad Request Error

You encounter this error because every time a clien tries to access your site via HTTP, the request is redirected to HTTPS. It’s because the nginx expects SSL to be used in the transaction yet the original reques t(received via port 80) was plain HTTP, it complains with the error.

On the other hand, if a client uses https://example.com, they will not encounter the above error. In addition, if you have other websites configured not to use SSL, nginx will try to use HTTPS by default for them resulting to the above error.

To fix this error, comment out the line below in your configuration or set it to off.

#ssl on 
OR
ssl off

Save and close the file. Then restart the nginx service.

# systemctl restart nginx
OR
$ sudo systemctl restart nginx

This way, you can enable nginx to handle both HTTP and HTTPS requests for multiple server blocks.

Finally, below is a list of articles about setting up SSL HTTPS on common Linux distributions and FreeBSD.

  1. Setting Up HTTPS with Let’s Encrypt SSL Certificate For Nginx on RHEL/CentOS
  2. Secure Nginx with Free Let’s Encrypt SSL Certificate on Ubuntu and Debian
  3. How to Secure Nginx with SSL and Let’s Encrypt in FreeBSD

That’s all for now. If you know of any other way to solve this error, please let us know via the feedback form below.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Photo of author

Aaron Kili is a Linux and F.O.S.S enthusiast, an upcoming Linux SysAdmin, web developer, and currently a content creator for TecMint who loves working with computers and strongly believes in sharing knowledge.


Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Ошибка 400 Bad Request «the plain http request was sent to https port» на Nginx довольно распространенная проблема, когда вы пытаетесь настроить Nginx для обработки запросов http и https + сертификат SSL. Как получить бесплатный сертификат  Let’s Encrypt, мы рассказывали в статье.

Данной инструкцией объясню причину и решение, что бы запросы к сайту Nginx отрабатывал корректно.
Перейдем к конфигурационному файлу Nginx. В CentOS, обычно, конфиг расположен в директории /etc/nginx/conf.d/. В Ubuntu и Debian — в директории /etc/nginx/sites-enabled/. Во FreeBSD в  /etc/nginx/nginx.conf. . Выглядит конфиг nginx у вас примерно так (убрал лишнюю информацию, что бы не нагружать):

server {
listen 80;
listen 443;
server_name adminwin.ru www.adminwin.ru;
root /home/myhome/app/public;
passenger_enabled on;

# Конфиги SSL / TLS
ssl on;
ssl_certificate /opt/nginx/ssl_keys/ssl.crt;
ssl_certificate_key /opt/nginx/ssl_keys/ssl.key;
....
}

проблема данного конфигурационного файла nginx в том, что при обращении по 80 порт (HTTP) на ваш сайт, веб сервер ожидает использование SSL, который должен использоваться только при обращении н 443 порт (HTTPS).
Исправим конфиг, закомментировав в нем строку с командой «ssl on;» или изменив команду на «ssl off;» и приведем его в следующий вид:

server {
listen 80;
listen 443;
server_name adminwin.ru www.adminwin.ru;
root /home/myhome/app/public;
passenger_enabled on;

# Конфиги SSL / TLS
#ssl on;
ssl off;
ssl_certificate /opt/nginx/ssl_keys/ssl.crt;
ssl_certificate_key /opt/nginx/ssl_keys/ssl.key;
....
}

Теперь у нас сайт по 80 порту (HTTP) открывается, а по 443 (HTTPS) не доступен.
Получается, что полностью исключить или включить ssl мы не можем, но можем указать конкретно использование ssl только для 443 портов (HTTPS).
Исправный конфиг будет выглядеть следующим образом:

server {
listen 80;
listen 443 default ssl;
server_name adminwin.ru www.adminwin.ru;
root /home/myhome/app/public;
passenger_enabled on;

# Конфиги SSL / TLS
#ssl on;
ssl_certificate /opt/nginx/ssl_keys/ssl.crt;
ssl_certificate_key /opt/nginx/ssl_keys/ssl.key;
....
}

В конечном конфиге Nginx мы явно указали использовать SSL для 443 запросов на сайт строчкой «listen 443 default ssl;«, в некоторых версиях срабатывает «listen 443 ssl;»

Напишите в комментариях, помогла статья решить проблему с ошибкой «Обычный HTTP-запрос был отправлен на HTTPS-порт» или нет.

I’m having a problem using a WCF call from a Windows service to my WCF service running on my web server. This call has been working for a number of weeks, but then stopped working all of a sudden, and has not worked since.

The exception I’m getting is:

General Error Occurred System.ServiceModel.CommunicationException: An error occurred while making the HTTP request

and then it says

This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.

The security I’m using on both ends is wsHttpBinding, without any kind of encryption. It also is just using HTTP — not HTTPS, so I’m not sure why it’s complaining about HTTPS.

The rest of the inner exception stack is:

SystemNet.WebException: The underlying connection was closed: An unexpected error occurred on a send.
—> System.IO.IOException: Unable to write data to the transport connection: An invalid argument was supplied.
—> System.Net.Sockets.SocketException: An invalid argument was supplied at System.Net.Sockets.Socket.MultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags) at System.Net.Sockets.NetworkStream.MultipleWrite(BufferOffsetSize[] buffers)

I should also note that the point in my program where this occurs is on the «Execute» line of the call to the web service — that is, right as soon as I call the web service and pass it the wrapped up DataContract object, it blows up.

All this service is doing is getting passed a large amount of XML (passed as a .NET object to the call on the client side), which it then does some work with. Probably about 100-200k of XML is being transmitted. I’ve raised the limits for the data sizes on both ends to over 6 megs, but that didn’t seem to help.

Any ideas?


Some more information on this issue:

When we duplicate the client environment locally, we find that we cannot upload large amounts of XML unless we make the following changes:
1. On the server, set the «maxRequestLength» to 100 MB (way higher than we are sending)
2. On the client, we set the value of maxItemsInObjectGraph under the dataContractSerializer tag to «2147483646».

With these changes, our local installation uploads successfully. However, the client’s install on their server still fails. What interesting to note is that once we made the maxRequestLength value change on the server, our test installation started throwing an error specifically relating to the maxItemsInObjectGraph setting. Whereas on our client’s server, still the original «HTTP.sys» error is happening.

As I noted before, we are not using SSL at all, and there are 2 other web services calls that execute and upload XML in the same way. However, since the non-working service call transmits more data, this appears to be a size issue.

However, if the issue the client is having were the same one our test install had, I don’t get why the client error message wouldn’t be related to the ObjectGraph error.

Is it possible that we’re just getting the generic «invalid parameter» «HTTP.sys» error for every possible error on the client (ie. it’s really getting the objectGraph error too, but just isn’t showing it?)

Понравилась статья? Поделить с друзьями:
  • Ошибка при отправке документов в контуре
  • Ошибка при отправке документов в еис
  • Ошибка при отправке документа в еис эп 1 уровня
  • Ошибка при отправке декларации через личный кабинет налогоплательщика
  • Ошибка при отправке декларации повторная регистрация первичного документа