The plain http request was sent to https port как исправить

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.

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 Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Ошибка 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-порт» или нет.

Setting up a server on any OS can be a bit of a challenge, especially when dealing with security protocols like SSL. If you incorrectly set up a server configuration to handle HTTP and HTTPS requests, you can run into quite a few errors.

One such error with Nginx is the “paint HTTP request was sent to HTTPS port”. The error arises when you haven’t enabled SSL on your Nginx configuration. Meaning when a client tries to open http://site.com (or HTTP port 80), the server will try to use HTTPS by default resulting in this error.

On the other hand, if a client tries to connect to https://site.com, the site will work just fine as the URL securely connects to the server. 

Also read: How to check Nginx_status?


How to fix this error?

Fixing this issue is relatively simple. Nginx expects SSL to be used when an original request connects via plain HTTP to port 80, enabling SSL to eliminate the error.  All you have to do is modify your Nginx configuration to enable (or disable) SSH access.

For reference, this is how the default configuration file in Nginx looks like. If you don’t want to change your existing configuration file, you can use this configuration to resolve the issue.

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;
        #}
}

Just open your configuration file and find the SSL toggle, which looks like ‘ssl on;’. Just uncomment the line containing the SSH instruction you want to implement (enabling or disabling) and save the file.

After that, you need to restart the Nginx server using the command below, and you’re good to go. 

sudo systemctl restart nginx

If you’re facing this error while using the Apigee API, you can check out this guide for possible causes and solutions.

Also read: Linux no space left on device: 3 Fixes

Yadullah Abidi

Someone who writes/edits/shoots/hosts all things tech and when he’s not, streams himself racing virtual cars.

You can contact him here: [email protected]

Добрый день

Хочу использовать только https и хочу сделать редирект с http на https

Делаю так

server {<br/>
 listen *:80;<br/>
 server_name example.com;<br/>
 rewrite ^(.*)$ https://$server_name$1 permanent;<br/>
}<br/>
<br/>
server {<br/>
 listen *:443;<br/>
 ...<br/>
}<br/>

и при переходе на example.com

The plain HTTP request was sent to HTTPS port

https работает нормально

enginx использую в качестве фронт-енда, апач в качестве бекенда.

Хочу чтобы все соединения до nginx шли в зашифрованном виде, а между nginx apache уже обычный http.

Что я делаю не так? Может есть какой-либо другой способ решить поставленную задачу?


  • Вопрос задан

    более трёх лет назад

  • 110040 просмотров

а если так?

server {
  listen *:80;
  server_name example.com;
  proxy_set_header Host example.com;
  location / {
    rewrite ^(.*)$ https://example.com$1 permanent;
  }
}
server {
  listen *:443 ssl;
  server_name example.com;
  proxy_set_header Host example.com;
  location / {
    proxy_pass http://127.0.0.1:8080;
  }
}

Пригласить эксперта

Согласно официальной документации рекомендуют использовать такую конструкцию:

server {
        listen 80;
        server_name example.com;
        return 301 https://$server_name$request_uri;  # enforce https
#        rewrite ^(.*) https://www.example.com$uri permanent;
}

еще хороший вариант:

if ($ssl_protocol = "") {                                
                                rewrite ^/(.*) https://$server_name/$1 permanent;
}

У меня такой код для определенных location сделан. К примеру чтобы admin и иже с ними только через https работыли.

Сделайте так:
rewrite ^(.*) https://$server_name$1 permanent;

Блин, начал писать про редирект в коде, и почему-то вспомнил про .htaccess. Некрасиво получилось :)
В общем искать надо, где 443 стоит рядом с http://

Поправьте на
listen *:443 ssl;

Попробуйте так:

rewrite ^(.*) https://$host$1 permanent;

Только что ради эксперимента проделал такой редирект. Причем с буква-в-букву приведенным конфигом, за исключением server_name-ов. Все работает отлично. Видимо проблема не в данной части, а далее, например, в описании проксирования на апач.
proxy_redirect off; не забыли?

>400 Bad Request The plain HTTP request was sent to HTTPS port
Я думаю что тцт просто сам браузер не знает что надо посылать шифрованный запрос. и посылает назащифрованный.
Может стоит попробовать сделать редирект через сам движок
PHP:

header('Location: https://.........../');

не забываем в виртуалхосты апача добавить SetEnvIf X-Forwarded-Proto https HTTPS=on


  • Показать ещё
    Загружается…

Сбер

Нижний Новгород

от 170 500 ₽

10 февр. 2023, в 04:49

50000 руб./за проект

10 февр. 2023, в 02:20

3000 руб./за проект

10 февр. 2023, в 01:33

1500 руб./за проект

Минуточку внимания

NGINX is a popular web server used by millions of websites and organizations. It is capable of handling high traffic websites and offers tons of features. However, sometimes you may get an error ‘Plain HTTP request was sent to HTTPS port’ in NGINX. In this article, we will learn how to fix this error.

This error occurs when you try to configure both HTTP and HTTPS connections on the same NGINX server.

Let us say you have the following configuration in your NGINX server. We have created two server blocks one for http and the other for https. The server block for HTTP requests listens to port 80 while server block for HTTPS requests listens to port 443. All requests sent to HTTP server block are redirected to the server block that services HTTPS requests.

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;



        # 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;
        }
        ...
}

When you run the above configuration, you will most likely get the error ‘Plain HTTP Request Was Sent to HTTPS Port’. This is because, when users enter HTTP URLs such as http://example.com our NGINX server will try to redirect that request to the server handling HTTPS requests. But in this case, the server expects the request to use SSL. Since this did not happen, it shows the error.

On the other hand, if the user directly enters the HTTPS URL such as https://example.com they won’t get the error.

To fix this error, you need to open NGINX configuration file and comment out the following line or set ssl directive to off, highlighted in bold in above configuration.

#ssl on 
OR
ssl off

Save and close the file. Restart NGINX server to apply changes.

# systemctl restart nginx
OR
$ sudo systemctl restart nginx

In this article, we have learnt how to fix ‘plain HTTP request was sent to HTTPS port’ error in NGINX.

Also read:

How to Block USB Storage Devices in Linux
How to Disconnect Inactive or Idle SSH Sessions
How to Enable Debugging Mode in SSH
How to Copy Column to Another Column in MySQL
How to Add Header in CSV File Using Shell Script

Related posts:

Понравилась статья? Поделить с друзьями:
  • The pcie is different from the last startup как исправить
  • The path c programdata package cache ошибка
  • The password format is invalid onerpm как исправить
  • The parameter is incorrect 0x80070057 как исправить
  • The parallel port driver service failed to start due to the following error