Linux 400 bad request

400 Bad Request on nginx 1.14.0 Ubuntu

I have two websites admin.example.com and www.example.com . The admin website is developed in Django 2.2 and the front website is developed in Angular 8. Both websites are configured with Nginx 1.14.0 on Ubuntu 18.

Problem:

I have recently added SSL on these sites. While the admin site works good the frontend shows 400 bad request error with text «The plain HTTP request was sent to HTTPS port». I found this Dealing with nginx 400 «The plain HTTP request was sent to HTTPS port» error for the same problem but it’s not working in my case. My configuration for admin.example.com (Django):

server < listen 80; server_name admin.example.com; return 301 https://admin.example.com$request_uri; >server < listen 443 ssl; server_name admin.example.com; ssl off; ssl_certificate /root/ssl-bundle.crt; ssl_certificate_key /root/example.com.key; location = /favicon.ico < access_log off; log_not_found off; >location /static/ < root /home/raakesh/backend; >location / < include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; >> 
server < listen 80 default_server; server_name www.example.com; return 301 https://$server_name$request_uri; >server < listen 443 default_server ssl; server_name www.example.com; root /home/rohangular/websiteangular/dist/angular-website; index index.html index.htm; access_log /var/log/nginx/example.com/access.log; error_log /var/log/nginx/example.com/error.log; location / < try_files $uri $uri/ /index.html; >location = /favicon.ico < access_log off; log_not_found off; >ssl off; ssl_certificate /root/ssl-bundle.crt; ssl_certificate_key /root/example.com.key; > 

[info] 1533#1533: *247 client sent plain HTTP request to HTTPS port while reading client request headers, client: 188.166.28.57, server: www.example.com, request: «GET /main-es5.54e5eba613f299b8fae5.js HTTP/1.1», host: «www.example.com»

Another wired issue I am facing is, this example.com website sometimes automatically starts working and sometimes shows 400 error as described above. I am not able to understand while the first one is working but not the second one. Please help me if I have done something wrong or I missed anything.

Источник

Fix “The plain HTTP request was sent to HTTPS port” Error in Nginx

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.

Читайте также:  Asus eee pc 1005pxd linux

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.

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

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.

Читайте также:  Failed connection refused linux

To fix this error, comment out the line below in your configuration or set it to 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.

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.

Источник

Why am I getting 400 Bad Request?

I have just finished setting up a server on AWS ECS. All of the configurations are identical to a different server I have, except for Apache version (from 2.2 to 2.4) and PHP version (from 5.3 to 5.6). I have modified my index.php file to only printout the php_info(), but I keep getting:

Bad Request Your browser sent a request that this server could not understand. Additionally, a 400 Bad Request error was encountered while trying to use an ErrorDocument to handle the request. Apache/2.4.25 (Amazon) Server at xxx.yyy.com Port 80

I have looked at all the logs saved from my accesses and this is what I get from this specific access: error_log

[Tue Jan 24 16:20:46.154208 2017] [suexec:notice] [pid 32139] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Tue Jan 24 16:20:46.249527 2017] [auth_digest:notice] [pid 32146] AH01757: generating secret for digest authentication . [Tue Jan 24 16:20:46.250415 2017] [lbmethod_heartbeat:notice] [pid 32146] AH02282: No slotmem from mod_heartmonitor [Tue Jan 24 16:20:46.276823 2017] [mpm_prefork:notice] [pid 32146] AH00163: Apache/2.4.25 (Amazon) OpenSSL/1.0.1k-fips configured -- resuming normal operations [Tue Jan 24 16:20:46.276840 2017] [core:notice] [pid 32146] AH00094: Command line: '/usr/sbin/httpd' 
90.152.127.182 - - [24/Jan/2017:16:21:03 +0000] "GET / HTTP/1.1" 400 437 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" 90.152.127.182 - - [24/Jan/2017:16:21:04 +0000] "GET /favicon.ico HTTP/1.1" 400 437 "http://xxx.yyy.com/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" 
90.152.127.182 - - [24/Jan/2017:16:12:24 +0000] "GET / HTTP/1.1" 400 434 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" 90.152.127.182 - - [24/Jan/2017:16:12:25 +0000] "GET /favicon.ico HTTP/1.1" 400 434 "https://xxx.yyy.com/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" 

Источник

Читайте также:  Linux apache mysql php server

400 bad request nginx — как исправить ошибку

Ошибка 400 bad request nginx означает, что сделан неверный запрос.

Ошибка может возникать по разным причинам, всё зависит от используемой конфигурации и приложения.

Если речь идет о запросах к базе данных или API — причина может быть в работе бэкенда. Например, недостаточное количество знаков в поле БД.

В случае если ошибка возникает при обращении к странице сайта — причина обычно в Nginx и размерах буферов, которые задаются в конфигурационных файлах.

Рассмотрим подробнее этот случай, он самый типичный.

Ошибка 400 bad request nginx

Объем заголовков в запросе может быть различным. Если он велик и лимит, установленный в конфигурации, не позволяет их обработать — возникнет ошибка.

Ошибка исправляется добавлением в секцию http конфигурационного файла nginx.conf следующей директивы:

large_client_header_buffers 2 12k;

Тестируем конфигурацию, убеждаемся в том, что ошибок в выводе нет

Затем перечитываем конфигурация веб-сервера чтобы он увидел новые директивы и значения паратетров.

Если параметры уже добавлены можно попробовать увеличить их значения, в 2, в 4 раза.

С каждой итерацией нужно тестировать конфигурацию с помощью nginx -t, перезапускать процесс nginx -s reload и проверять выполняя тот же запрос при котором была ошибка 400 bad request nginx.

Дополнительно можно проверить логи Nginx

Если ошибка возникает периодически — в логе доступа можно найти при помощи grep все случаи получения ответа 400 по уникальным характеристикам запроса: комбинации даты, времени, ip адреса клиента. Затем сопоставить данные с записями в error.log — логе ошибок.

В access.log будут запросы, которые выполнялись при обращении к сайту.

Пример запроса с кодом ответа 400 приведен на скриншоте:

400 bad request nginx

Также есть другие буферы Nginx, на которые стоит обратить внимание (ссылка на статью про буферы была выше). Особенно если сервер обслуживает нагруженный проект.

Читайте про конфигурацию веб-сервера Nginx: структуру файлов с настройками и контексты.

Источник

Оцените статью
Adblock
detector