How to create a https server on localhost?

Member

by aubrey , in category: PHP General , 2 months ago

How to create a https server on localhost?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 2 months ago

@aubrey 

To create a HTTPS server on localhost, you will need a SSL certificate. You can generate a self-signed certificate for testing purposes using OpenSSL:

  1. Install OpenSSL on your system if you don't already have it installed.
  2. Open a terminal or command prompt.
  3. Use the following command to generate a new self-signed certificate:
1
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365


  1. Follow the prompts to enter information for the certificate.
  2. This will create two files in the current directory: key.pem (private key) and cert.pem (certificate).


Once you have the SSL certificate, you can create a HTTPS server using a Node.js script. Here is an example using Node.js:

  1. Create a new file (e.g., server.js) and add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Hello HTTPS!');
}).listen(443);


  1. Save the file and run it using Node.js by running the following command in the terminal or command prompt:
1
node server.js


  1. Your HTTPS server should now be running on https://localhost.


Please note that self-signed certificates are not recommended for production use as they are not trusted by default. For production use, you should obtain a valid SSL certificate from a trusted certificate authority.