HOWTO: SSL и NGINX

В данной заметке я расскажу как быстро привязать ssl сертификат к nginx. Испытания мы проведем тестовом сервере с тестовым сертификатом, который запросим у Comodo.

Итак, для начала определимся что у нас есть. А есть у нас один nginx сервер который смотрит в Интернет. И, для простоты, один внутренний (с ip 10.10.10.10) для которого и будет создаваться стандартное и ssl подключение. Конечно, серверов может быть сколько угодно. Но мы с вами сейчас не будем усложнять.

Для начала нам необходимо создать CSR-запрос на сертификат. Бесплатно можно его сделать либо напрямую у Comodo, либо через сайт http://www.freessl.su/. Мы будет делать через http://www.freessl.su/.

Конфигурационные файлы от nginx у меня лежат в каталоге /etc/nginx. Создаем там подкаталог ssl и переходим в него.

 mkdir /etc/nginx/ssl
 cd /etc/nginx/ssl

Далее необходимо создать CSR запрос. Для этого сначала создадим файл приватного ключа следующей командой:

openssl genrsa -des3 -out secure.website.ru.key 2048

Если вы хотите создать файл ключа без пароля, то введите следующую команду

openssl genrsa -out secure.website.ru.key 2048

Далее создадим файл запроса на генерацию сертификата. Для этого пишем команду и заполняем необходимые поля:

openssl req -new -key secure.website.ru.key -out secure.website.ru.csr

После этого будет сгенерирован файл /etc/nginx/ssl/secure.website.ru.csr. Скопируем его содержимое и идем на сайт www.freessl.su. Там заполняем поля ФИО, Телефон, email и вставляем содержимое файла secure.website.ru.csr в поле CSR. Нажимаем далее, выбираем подходящий контактный email. После этого на почтовый ящик придет письмо с просьбой подтвердить создание ssl сертификата. В письме будет указан код подтверждения. Перейдите по ссылке в письме и введите код.

Через некоторое время вам придет архив с сертификатом и файлом с промежуточными сертификатами. Скопируйте содержимое secure_website_ru.ca-bundle в /etc/nginx/ssl/secure.website.ru.crt.

cat secure_website_ru.crt >> /etc/nginx/ssl/secure.website.ru.crt
cat secure_website_ru.ca_bundle >> /etc/nginx/ssl/secure.website.ru.crt

На этом формирование сертификата закончено.

Переходим к настройке nginx. Для нашего случая конфигурация /etc/nginx/nginx.conf будет выглядеть следующим образом:

user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
 pid /var/run/nginx.pid;
 events {
 worker_connections 2048;
 }
 http {
 upstream www {
 server 10.10.10.10 weight=1 max_fails=3 fail_timeout=120;
 }
include /etc/nginx/mime.types;
 default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
 '$status $body_bytes_sent "$http_referer" '
 '"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#Секция для стандартного подключение по 80 порту
 server {
 listen 80;
 server_name secure.website.ru;
 reset_timedout_connection on;
 location / {
 proxy_pass http://www/;
 proxy_next_upstream error timeout invalid_header http_500 http_503;
 proxy_set_header Host $host;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_redirect off;
 proxy_connect_timeout 100;
 }
 }
# Секция для подключения по ssl
 server {
 listen 443 ssl;
 server_name secure.website.ru;
access_log logs/ssl-access.log;
 error_log logs/ssl-error.log;
ssl_certificate ssl/secure.website.ru.crt;
 ssl_certificate_key ssl/secure.website.ru.key;
 ssl_verify_depth 3;
keepalive_timeout 60;
 location / {
 proxy_pass http://www/;
 proxy_next_upstream error timeout invalid_header http_500 http_5
 proxy_set_header Host $host;
 proxy_set_header X-Real-IP $remote_addr;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header X-Forwarded-Proto https;
 proxy_redirect off;
 }
 }
 }
Сохраняем и перезапускаем nginx.
# service nginx reload
Вдаваться в детали настроек я не хочу. Про них очень хорошо написано в официальной документации nginx.
Единственное что хотелось бы подчеркнуть, что если вы хотите на 1 сервер повесить несколько разных ssl сертификатов на порт 443, то просто добавить такую конфигурацию не получится:
server {
 listen 443;
 server_name www.example.com;
 ssl on;
 ssl_certificate www.example.com.crt;
 ...
 }
server {
 listen 443;
 server_name www.example.org;
 ssl on;
 ssl_certificate www.example.org.crt;
 ...
 }

В такой конфигурации браузер получит сертификат первого сервера, т.е. www.example.com, независимо от запрашиваемого имени сервера. Это связано с поведением протокола SSL. SSL-соединение устанавливается до того, как браузер посылает HTTP-запрос, и nginx не знает имени запрашиваемого сервера. Следовательно, он лишь может предложить сертификат сервера по умолчанию. Решение данного вопроса вы можете найти по ссылке.

На этом базовая настройка nginx законена.

40 комментариев к “HOWTO: SSL и NGINX

  1. The next time I review a blog site, I hope that it does not disappoint me as long as this set. I indicate, I understand it was my option to check out, yet I really believed youd have something interesting to state. All I hear is a lot of whining about something that you can take care of if you werent too hectic seeking attention.

  2. With havin so much content and articles do you ever run into any issues of plagorism or copyright violation? My blog has a lot of completely unique content I’ve either authored myself or outsourced but it appears a lot of it is popping it up all over the web without my authorization. Do you know any techniques to help reduce content from being ripped off? I’d definitely appreciate it.

  3. The next time I review a blog, I wish that it doesn’t disappoint me as high as this set. I suggest, I understand it was my option to read, but I in fact assumed youd have something fascinating to state. All I hear is a number of whining about something that you could repair if you werent as well active seeking focus.

  4. Can I just say what a relief to discover someone that in fact understands what theyre discussing online. You most definitely understand just how to bring an issue to light and also make it vital. Even more people need to read this and also understand this side of the story. I cant believe youre not more prominent because you most definitely have the present.

  5. I?m impressed, I need to say. Truly seldom do I experience a blog that?s both educative and enjoyable, and let me inform you, you have struck the nail on the head. Your concept is superior; the problem is something that not enough individuals are speaking wisely around. I am very delighted that I came across this in my look for something associating with this.

  6. Hey there! This is kind of off topic but I need some guidance from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about making my own but I’m not sure where to start. Do you have any points or suggestions? Many thanks

  7. Hey there this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding experience so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!

  8. Fascinating blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple tweeks would really make my blog shine. Please let me know where you got your theme. With thanks

  9. Hey! I could have sworn I’ve been to this blog before but after checking through some of the post I realized it’s new to me. Nonetheless, I’m definitely delighted I found it and I’ll be book-marking and checking back often!

  10. Appreciating the time and effort you put into your blog and in depth information you offer. It’s awesome to come across a blog every once in a while that isn’t the same old rehashed material. Great read! I’ve bookmarked your site and I’m including your RSS feeds to my Google account.

  11. After looking into a number of the blog articles on your web page, I really like your technique of writing a blog. I bookmarked it to my bookmark webpage list and will be checking back in the near future. Take a look at my website too and tell me what you think.

  12. Having read this I thought it was rather enlightening. I appreciate you finding the time and effort to put this information together. I once again find myself personally spending a lot of time both reading and leaving comments. But so what, it was still worth it!

  13. Its like you read my thoughts! You seem to grasp so much about this, like you wrote the book in it or something. I think that you could do with a few percent to pressure the message home a bit, but other than that, that is excellent blog. A great read. I’ll definitely be back.

  14. After study a few of the post on your site currently, and also I genuinely like your means of blog writing. I bookmarked it to my book marking site listing as well as will certainly be examining back soon. Pls have a look at my web site also and also let me understand what you believe.

  15. Howdy would you mind letting me know which webhost you’re working with? I’ve loaded your blog in 3 different web browsers and I must say this blog loads a lot faster then most. Can you suggest a good internet hosting provider at a reasonable price? Cheers, I appreciate it!

Оставить ответ к website design in mangalore Отменить ответ

Ваш адрес email не будет опубликован. Обязательные поля помечены *