本人github

是的,HTTPS 可以使用非 443 端口进行通信。虽然 443 端口是 HTTPS 的默认端口,但并没有限制 HTTPS 必须使用这个端口。你可以在任何开放的端口上配置和使用 HTTPS。

配置示例

以下是一些常见场景和配置示例,展示如何在非 443 端口上使用 HTTPS。

配置 Web 服务器使用非 443 端口
Nginx

在 Nginx 配置文件中,可以指定一个非 443 端口来处理 HTTPS 请求。例如,使用 8443 端口:

server {
    listen 8443 ssl;
    server_name example.com;

    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    location / {
        root /var/www/html;
        index index.html index.htm;
    }
}

保存配置文件并重新加载 Nginx:

sudo systemctl reload nginx
Apache

在 Apache 配置文件中,也可以指定一个非 443 端口来处理 HTTPS 请求。例如,使用 8443 端口:

<VirtualHost *:8443>
    ServerName example.com

    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/example.com.crt
    SSLCertificateKeyFile /etc/ssl/private/example.com.key

    DocumentRoot /var/www/html
    <Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

保存配置文件并重新加载 Apache:

sudo systemctl reload apache2
访问使用非 443 端口的 HTTPS 服务

在浏览器中,直接指定端口号即可访问非 443 端口上的 HTTPS 服务。例如,使用 https://example.com:8443:

https://example.com:8443
使用命令行工具访问非 443 端口的 HTTPS 服务
使用 curl
curl -k https://example.com:8443
使用 wget
wget --no-check-certificate https://example.com:8443
在编程语言中访问非 443 端口的 HTTPS 服务
Python

使用 requests 库访问非 443 端口的 HTTPS 服务:

import requests

response = requests.get('https://example.com:8443', verify=False)
print(response.content)
Node.js

使用 axios 库访问非 443 端口的 HTTPS 服务:

const axios = require('axios');

axios.get('https://example.com:8443', { httpsAgent: new require('https').Agent({ rejectUnauthorized: false }) })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
Java

使用 HttpURLConnection 访问非 443 端口的 HTTPS 服务:

import java.net.*;
import java.io.*;
import javax.net.ssl.*;

public class Main {
  public static void main(String[] args) throws Exception {
    // Configure SSL context to trust all certificates
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[]{new X509TrustManager() {
      public X509Certificate[] getAcceptedIssuers() { return null; }
      public void checkClientTrusted(X509Certificate[] certs, String authType) { }
      public void checkServerTrusted(X509Certificate[] certs, String authType) { }
    }}, new SecureRandom());

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    URL url = new URL("https://example.com:8443");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setHostnameVerifier((hostname, session) -> true);

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      System.out.println(inputLine);
    }
    in.close();
  }
}

总结

HTTPS 可以使用非 443 端口进行通信,只需要在服务器配置中指定不同的端口,并在客户端访问时使用相应的端口号即可。这样可以灵活地部署 HTTPS 服务,不局限于默认的 443 端口。

更多推荐