Перейти к содержимому

Как сделать localhost https

  • автор:

Сертификаты для localhost

Иногда разработчикам нужен сертификат для доменного имени “localhost” — для локальной разработки, или для распространения внутри нативных приложений для взаимодействия с web-приложением. Let’s Encrypt не предоставляет сертификатов для “localhost”, т.к. во-первых, у этого доменного имени нет определённого владельца, и во-вторых, нет домена первого уровня — например, “.com” или “.net”. Теоретически, возможно настроить доменное имя так, чтобы оно указывало на адрес 127.0.0.1 , и выпустить для него сертификат после прохождения проверки DNS. Тем не менее, есть более удачные решения. Тем не менее, есть более удачные решения.

Для локальной разработки

При разработке web-приложения обычно запускают локальный web-сервер (Apache, Nginx), настроенный на http://localhost:8000/ . Однако, браузеры по-разному обрабатывают HTTP- и HTTPS-запросы. На HTTPS-странице попытка загрузить Javascript по HTTP-протоколу будет заблокирована. Поэтому, при локальной разработке, используя HTTP, скрипты будут загружаться нормально, но после выкладки на рабочие HTTPS-серверы возникнут проблемы. Чтобы избежать такой ситуации, нужно настроить доступ по HTTPS на локальном web-сервере. Но как избавиться от постоянных сообщений об ошибке сертификата? Как увидеть “зелёный замОк” в адресной строке?

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

Для нативных приложений, взаимодействующих с web-приложениями

Время от времени, разработчики вынуждены выпускать загружаемые нативные приложения, для расширения функциональности и совместного использования с web-приложениями. Например, десктоп-приложения Dropbox и Spotify умеют сканировать файлы на дисках компьютера, что невозможно для web-приложений. Общий подход в реализации таких нативных приложений состоит в запуске локального web-сервера, и обмену данными с web-приложением через XMLHTTPRequest (XHR) или WebSockets. Web-приложения, как правило, используют HTTPS, поэтому XHR- или WebSockets-запросы по небезопасному протоколу HTTP будут отклонены. Это называется “блокировка смешаного контента” (Mixed Content Blocking). Для взаимодействия с web-приложением, нативное приложение должно быть безопасным.

С одной стороны, современные браузеры считают http://127.0.0.1:8000/ “потенциально заслуживающим доверие” URL-ом, потому что он локальный. Отправленный на 127.0.0.1 трафик гарантированно не уйдёт за пределы компьютера, соответственно, считается безопасным для перехвата по сети. Это означает, что если web-приложение использует HTTPS, а нативное приложение запущено на 127.0.0.1 , то обе программы могут успешно взаимодействовать по XHR. С другой стороны, для localhost это ещё не работает. А WebSocket-ы игнорируют и 127.0.0.1 , и localhost .

Возможно, вы захотите обойти эти ограничения, настроив указание произвольного доменного имени в глобальном DNS на адрес 127.0.0.1 (например, localhost.example.com ), выпустив сертификат для этого домена, распространяя сертификат и соответствующий ему закрытый ключ внутри нативного приложения, и настроив взаимодействие по https://localhost.example.com:8000/ вместо http://127.0.0.1:8000/ . Не делайте этого! Это подвергнет пользователей риску, и сертификат может быть отозван.

Используя доменное имя вместо IP-адреса, вы позволяете злоумышленникам запустить атаку Man in the Middle (MitM) в процессе поиска IP-адреса по доменному имени (DNS Lookup), и внедрить ответ, который укажет на другой IP-адрес. Атакующий может притвориться нативным приложением, подделывая запросы к web-приложению, что скомпрометирует аккаунт в web-приложении.

Успех атаки MitM возможен потому, что вы вынуждены распространять закрытый ключ для сертификата вместе с нативным приложением. Соответственно, любой, кто скачает это приложение, получит копию ключа. Этим вы скомпрометируете закрытый ключ, и Удостоверяющий Центр (УЦ) отзовёт сертификат, как только узнает об этом. У множества нативных приложений были отозваны их сертификаты из-за распространения закрытого ключа.

К сожалению, это сужает список безопасных способов взаимодействия нативных и web-приложений. И ситуация может ещё больше усложниться в недалёком будущем, если браузеры продолжат затруднять доступ к localhost.

Так же нужно отметить, что web-сервисы с доступом к нативному API изначально небезопасны, потому что сайты, которые вы не намеревались авторизовать, могут получить доступ к этому API. Если решите углубиться в изучение проблемы, обратите внимание на Cross-Origin Resource Sharing, использование заголовка ответа Access-Control-Allow-Origin, и надёжного HTTP-парсера. Потому как даже серверы, не прошедшие подтверждение, могут посылать предварительные запросы, эксплуатирующие уязвимости в HTTP-парсере.

Создание и поверка собственных сертификатов

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

Простейший способ сгенерировать закрытый ключ и самоподписанный сертификат для localhost — выполнить следующую команду из пакета openssl:

Вы можете сконфигурировать локальный web-сервер, используя файлы localhost.crt и localhost.key, добавив localhost.crt в список доверенных корневых сертификатов.

Если вам требуется чуть больше реализма в сертификатах для локальной разработки, попробуйте minica для создания собственного корневого сертификата, и выпуска конечных сертификатов, подписанных корневым. В итоге вы будете импортировать корневой сертификат вместо самоподписанных конечных сертификатов.

Также, вы можете использовать доменное имя с точками внутри (например, www.localhost ), добавив в файл /etc/hosts как алиас адреса 127.0.0.1 . Этот подход чуть изменит способ обработки браузерами хранилища для cookie.

Let’s Encrypt — это бесплатный, автоматизированный и открытый Центр Сертификации, созданный для вас некоммерческой организацией Internet Security Research Group (ISRG).

How to create a https server on localhost

enter image description here

It’s really easy to use and only takes few secs to run. It is as simple as downloading your system version. Unzip and run ngrok.exe . It will open a command line type of window. Make sure your Apache server or the one you use is running.

Then to only listen on an HTTPS tunnel endpoint run the following

or on whatever port you need https to be installed.

Open browser and type https://localhost/myApp you will see it works.

And if you type http://localhost/myApp it also works.

Hope this is helpful to anyone for a fast solution.

Balloon Fight's user avatar

I use Caddyserver with config like this:

You need to do two things:

  • generate a self-signed SSL certificate and
  • add it to the trusted certificates

Managed to do this on a macOS like so:

  • In order to generate the SSL certificate, run the follosing command in a terminal (according to the instructions from Let’s Encrypt):
  • And to add the certificate to the trusted certificates, ran the following command (suggested on this blog):

If this is meant for testing and you don’t need a valid cert (which seems to be the case since you’re using «localhost») you can use a «self-signed» cert, just make sure to configure nginx to point to those.

I could explain the details, but there’s actually a great post about that on Digital Ocean community tutorials:

just be sure to adapt the port (443) if you want to listen on 8000.

I finally set up my create-react-app https dev server

the reason why I’m doing this is to test device motion API on a mobile device.

generate cert files.

use LAN IP address instead of "localhost", because we will open our https page on a mobile device that has connected to the same WiFi.

create a .env file to set env variables

start the dev server

last but not least, install the cert file on the mobile device, the .pem file generated by mkcert is located in

/Library/Application Support/mkcert in my case.

install cert file on an Android device

install cert file on an iOS device

serve the .pem file on a static server, and open the file address on Safari

Littlee's user avatar

Assuming you are using node.js, then http-server has -S or —ssl with -C and -K to enable https.

Adriano's user avatar

Qiulang's user avatar

A very simple way is using local-ssl-proxy

The solution provided by Balloon Fight is absolutely what I was looking for and it works. But the command mentioned didn’t work for me, so here is what worked for me.

I am using Lubuntu 20.04 LTS (64-bit).

Lubuntu is a lightweight Linux flavor using Debian, Ubuntu and LXDE as its base.

Steps for OSX would probably be similar. Steps for Windows and Ubuntu GNOME are also mentioned.

Go to ngrok and create an account.

Download ngrok and install.

For Windows, just unzip the file and open it. It’ll run in cmd.

For Ubuntu GNOME, you would probably be able to run the file directly in terminal.

For Lubuntu (or if previous didn’t work for you). Move the file as follows:

If the file had directly opened up in terminal or cmd. Copy and paste the command from your profile on ngrok into cmd or terminal. The command looks like this:

./ngrok authtoken <your_auth_token>

If you are on Lubuntu, or if the file did not open directly in terminal. Change directory as follows:

And then copy and paste the command from your profile on ngrok into terminal. The command looks like this:

Run your server. Nodejs or what you usually use.

If you are still in the same directory as ‘ngrok’ file. Copy and paste the following command into terminal or cmd:

ngrok http 3000 -host-header="localhost:3000"

Change 3000 to the port you are using for the local server.

If you are out of ‘ngrok’ file’s directory. Open it up in terminal or cmd.

For Lubuntu, use the following command to change directory:

Then run the command:

Change 3000 to the port you are using for the local server.

  1. Copy and paste the HTTPS link, in the second ‘Forwarding’ row, to your browser.

The link looks something like this: https://12fab5c82c57.ngrok.io

For the next time you are required to do it. Just repeat step 4, 5 and 6.

cecilemuller / 2019-https-localhost.md

This focuses on generating the certificates for loading local virtual hosts hosted on your computer, for development only.

Do not use self-signed certificates in production ! For online certificates, use Let’s Encrypt instead (tutorial).

Certificate authority (CA)

Generate RootCA.pem , RootCA.key & RootCA.crt :

Note that Example-Root-CA is an example, you can customize the name.

Domain name certificate

Let’s say you have two domains fake1.local and fake2.local that are hosted on your local machine for development (using the hosts file to point them to 127.0.0.1 ).

First, create a file domains.ext that lists all your local domains:

Generate localhost.key , localhost.csr , and localhost.crt :

Note that the country / state / city / name in the first command can be customized.

You can now configure your webserver, for example with Apache:

Trust the local CA

At this point, the site would load with a warning about self-signed certificates. In order to get a green lock, your new local CA has to be added to the trusted Root Certificate Authorities.

Windows 10: Chrome, IE11 & Edge

Windows 10 recognizes .crt files, so you can right-click on RootCA.crt > Install to open the import dialog.

Make sure to select «Trusted Root Certification Authorities» and confirm.

You should now get a green lock in Chrome, IE11 and Edge.

Windows 10: Firefox

There are two ways to get the CA trusted in Firefox.

The simplest is to make Firefox use the Windows trusted Root CAs by going to about:config , and setting security.enterprise_roots.enabled to true .

The other way is to import the certificate by going to about:preferences#privacy > Certificats > Import > RootCA.pem > Confirm for websites .

For OSX (tested in Big Sur) it’s also possible to add the trusted certificate via CLI for your localhost project, here are all the steps:

Extra steps for cleanup

hi guys it didn’t work for me. kindly help me.

my setup —
Windows 10 OS
apache2(on ubuntu server) installed in VirtualBox VMS.
generated for domain linux.vm
in my windows hosts file — I added an entry for vm IP to linux.vm domain.
also i install rootCA.crt file in windows 10. by right click -> install

Note — my apache2 is accessible on windows 10’s chrome without https, but when i tried https, it gives error that «this certificate can’t be verified upto a trusted authority.«

You can also add IP.1 = 127.0.0.1 under [alt_name]

Thank you. Works like a charm.

I’m trying to get local tomcat working via ssl and following the above i have

localhost.crt
localhost.csr
localhost.key

but i need key.pem, cert.pem and chain.pem

What have i missed?

First, create a file domains.ext that lists all your local domains:

where this file should be created?

good! easy and fast, thank you!

The only one that worked after trying multiple solutions, easy and clear, thanks man

Is it possible to renew (and add new domains), or would you have to redo everything?

Thank you for sharing! It works great for my local development environment

First, create a file domains.ext that lists all your local domains:

where this file should be created?

In the same directory where the openssl command is executed.

Thank you for this, I had to reduce the validity for the localhost.crt to 397 days as that is now the maximum validity period. See this post about it, it might be worth updating the command with the new maximum.

Thank you so much! For a quick fix on local development environments, this beats messing with openssl .

If you need ready to use SSL certificates for localhost you can have a look at https://github.com/pryv/rec-la
https://.rec.la/ => https://localhost/

Certificate import error

The Private Key for this Client Certificate is missing or invalid

when i import certificate in chrome browser.
https://prnt.sc/1y2i7ev

Still Working!. Thanks @cecilemuller

Note that if you are generating for localhost, in the commands for «Generate localhost.key, localhost.csr, and localhost.crt:» the CN in the first command should be «. /CN=localhost», not «. /CN=localhost.local» otherwise Chrome (and maybe others) won’t like it.

Command: openssl x509 -req -sha256 -days 1024 -in localhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile domains.ext -out localhost.crt

OutPut: C:\xampp\htdocs\SSL>openssl x509 -req -sha256 -days 1024 -in localhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile domains.ext -out localhost.crt
Can’t open «domains.ext» for reading, No such file or directory
78030000:error:80000002:system library:BIO_new_file:No such file or directory:crypto\bio\bss_file.c:67:calling fopen(domains.ext, r)
78030000:error:10000080:BIO routines:BIO_new_file:no such file:crypto\bio\bss_file.c:75:

for me all steps work smoothly otherwise useless effort wont help because things are new and confusing.

How to get HTTPS working on localhost

This is a complete tutorial on how to get HTTPS working on localhost or any local domains. The main part is about manual SSL certificate creation. It is worth to now almost low-level details. If you need just a quick and easy setup, go to the end of the article where you will find other solutions.

What is this tutorial about:

  • How to set up local a domain
  • How to create a self-signed SSL certificate (or more accurately, TLS certificate)
  • How to configure Nginx to use an SSL certificate
  • How to run Nginx with HTTPS configured in a Docker container using docker-compose
  • Solutions without manual certificate creation

I am using Linux so this tutorial is for Linux OS. If you use Windows, you can run the same commands using the Git Bash emulator or WSL (Windows Subsystem for Linux). Though I didn’t try it, some commands may not work. Anyway, the setup path is the same. Only commands may differ.

We will use Docker with docker-compose and Nginx at the end to test if HTTPS works.

Why you might need an HTTPS for local domain

There are some reasons you might need to have HTTPS enabled for local domain:

  • You may need it to implement OAuth. For example, if you’re implementing Facebook login button on your website, it requires HTTPS to test it locally
  • If you have a local domain configured in the “hosts” file, and you want to test Service worker locally
  • Check if your web app redirects work as expected

Set up a local domain

You can use “localhost” as a domain name or create a local custom domain for development purposes. If you decide to continue with “localhost”, just skip this part and go to the next.

I will use “myapp.local” domain name as an example throughout the tutorial. You can use any domain you want.

To create a local domain you need to add a new record to the “hosts” file.

Open “/etc/hosts” file using “nano” or “vim” editor. In most cases, you will need to add “sudo” to have permission to edit and save the file. I am using “nano” editor in the command below.

Add a new line with a domain name you want.

This will map “myapp.local” domain (or any domain name you chose) to 127.0.0.1 IP. This IP is mapped to localhost in the same file.

Save and close the editor. Now when you start the Nginx server (i.e. if you use Docker from this tutorial), you can use myapp.local domain in the address bar in the browser.

Create Root self-signed SSL certificate

You can use a root certificate to create any number of local certificates. Place root certificate in the project folder or in any global folder to reuse it for any local project.

I created a new folder “local-root-ca” in the user’s home directory.

Run “genrsa” command in that folder to create a private RSA key.

Then create self-signed root CA (Certificate authority) certificate with the command below.

The “req” command creates a self-signed certificate for use as root CA.

You will be prompted to enter some certificate information. I used all default so just hit Enter for every prompt.

OpenSSL req command output screenshot

The output will look like this.

The next step is to add a self-signed root CA certificate to the trusted certificates in the browser. You will find tutorials for the Chrome and Firefox browsers below.

Add self-signed SSL certificate to the trusted in Chrome browser

I used version 90 of the Chrome browser.

Go to Settings (click three dots in the top right). Then click on the “Privacy and Security” menu on the left.

Chrome Privacy and Security menu screenshot

Chrome Security menu screenshot

Choose the “Security” menu item.

Chrome Manage Certificates menu screenshot

Then scroll to the bottom and choose the “Manage Certificates” section in the “Advanced” section.

Chrome Authority tab menu screenshot

Choose the “Authority” tab and click the “Import” button.

Then choose your previously created “rootCA.pem” file.

Chrome Trust this certificate screenshot

Check at least “Trust this certificate for identifying websites” and click OK.

That’s it. Now the Chrome browser trusts your certificates we will create lately.

Add self-signed SSL certificate to the trusted in Firefox browser

I used version 88 of the Firefox browser.

Firefox Privacy & Security menu screenshot

Go to Preferences (click on the hamburger menu in the top right first). Then click on the “Privacy & Security” menu item on the left.

Firefox Privacy & Security menu screenshot

Scroll down and find the “Security” section, and the “View Certificates” button here. Click it.

Firefox Authorities tab screenshot

Choose the “Authorities” tab and click the “Import” button. Find your previously created “rootCA.pem” file and choose it.

Firefox Downloading certificate dialog screenshot

In the next dialog check at least “Trust this CA to identify websites”. Then click the “Ok” button.

That’s it. Now Firefox browser trusts your certificates we will create lately.

Create domain SSL certificates common configuration

Prepare config files you will use to create domain SSL certificates. This is a one-time task. You can use it for multiple local domains lately.

Create a certificate config file named “server.csr.cnf” with the content below.

Create an extension file named “v3.ext” with the content below.

We will use the environment variable “SSL_DOMAIN_TEMP” here. It will be easier to reuse this config for the different domains.

Create a domain SSL certificate

Set the domain name we want to create an SSL certificate to the environment variable “SSL_DOMAIN_TEMP”.

Then create “crt” and “key” files. Both are parts of an SSL certificate. The “crt” file is a signed SSL certificate and the “key” file is a private key to it.

Create a “key” file command.

Create a “crt” file command.

Create new folder “certificates”. It might be in the project folder if you will use Docker Compose. Or in any folder, if you use Nginx without Docker.

Then copy domain SSL certificate files (“server.crt” and “server.key”) to the new folder. File “server.csr” can be deleted.

Nginx HTTPS configuration sample

If you’re using Docker from this tutorial, you need to create an Nginx configuration file. Create a new file “default.conf” in the project folder.

Here is the basic Nginx configuration for localhost with HTTPS enabled.

If you don’t use Docker, then use this config as a base for your local Nginx configuration.

Run Nginx using Docker Compose

You can skip this part if you don’t use Docker.

Create the “docker-compose.yml” file in the project directory. We already have folder “certificates” here.

Fill docker-compose.yml with the content below.

  • create a simple Nginx container from the lightweight Alpine image
  • map 80 (HTTP) and 443 (HTTPS) ports from the container
  • mount Nginx config and SSL certificate inside the Docker container

If you have another web server running, Docker can’t map ports 80 and 443. So either stop web server or change mapped ports, like “-81:80”. In this case, you will test the website using a URL with a port, i.e. http://localhost:81.

Test if localhost with HTTPS works

All steps completed. Now we can run the Docker container and check if HTTPS works.

Добавить комментарий

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