【Nginx】设置https和http同时使用同一个端口访问

以下是一个同时使用 HTTP 和 HTTPS 并通过 8070 端口的配置示例:

复制代码
server {
    listen 8070;
    server_name your_domain.com;

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

server {
    listen 8070 ssl;
    server_name your_domain.com;

    # SSL 证书和私钥的路径
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;

    # 可选:设置 SSL 协议和加密套件
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;

    # 可选:设置 HSTS 头,让浏览器强制使用 HTTPS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";

    location / {
        root /var/www/html;
        index index.html;
    }
}
  • 在上述配置中:
    • 第一个 server 块:
      • listen 8070;:让 Nginx 监听 8070 端口进行 HTTP 访问。
      • server_name your_domain.com;:指定服务器的域名,将 your_domain.com 替换为你的实际域名。
      • location /:将请求发送到 /var/www/html 目录下的静态文件,你可以根据需要修改,如将请求代理到其他服务器。
    • 第二个 server 块:
      • listen 8070 ssl;:让 Nginx 监听 8070 端口进行 HTTPS 访问。
      • ssl_certificatessl_certificate_key:指定 SSL 证书和私钥的路径。
      • ssl_protocolsssl_ciphers:配置 SSL 协议和加密套件,提高安全性。
      • add_header Strict-Transport-Security:启用 HSTS,让浏览器强制使用 HTTPS。
      • location /:与 HTTP 部分类似,将请求发送到 /var/www/html 目录下的静态文件,你可以根据需要修改。

注意事项

  • 虽然可以在同一端口同时提供 HTTP 和 HTTPS 服务,但这种配置可能会引起混淆,并且不是一个推荐的最佳实践。通常建议将 HTTP 服务和 HTTPS 服务分别部署在不同的端口,例如 80 端口用于 HTTP,443 端口用于 HTTPS,然后使用重定向将 HTTP 请求重定向到 HTTPS 以确保安全。以下是一个将 80 端口的 HTTP 请求重定向到 443 端口的 HTTPS 的示例:

    复制代码
    server {
        listen 80;
        server_name your_domain.com;
        return 301 https://$host$request_uri;
    }
相关推荐
掘根13 小时前
【jsonRpc项目】常用的零碎功能接口实现
网络协议·http
Filotimo_16 小时前
Nginx 的概念
运维·nginx
ps酷教程17 小时前
HttpPostRequestEncoder使用示例
http·netty
2501_9160088920 小时前
iOS开发APP上架全流程解析:从开发到App Store的完整指南
android·ios·小程序·https·uni-app·iphone·webview
lsswear21 小时前
swoole http 客户端
http·swoole
Shi_haoliu1 天前
SolidTime 在 Rocky Linux 9.5 上的完整部署流程
linux·运维·nginx·postgresql·vue·php·laravel
Arwen3031 天前
IP地址证书的常见问题有哪些?有没有特殊渠道可以申请免费IP证书?
服务器·网络·网络协议·tcp/ip·http·https
2501_915909062 天前
Charles 抓不到包怎么办?iOS 调试过程中如何判断请求路径
android·ios·小程序·https·uni-app·iphone·webview
2501_916007472 天前
iOS和iPadOS文件管理系统全面解析与使用指南
android·ios·小程序·https·uni-app·iphone·webview
zhengxianyi5152 天前
vue-cli build, vite build 生产部署刷新或弹窗404,页面空白修复方法
前端·javascript·vue.js·nginx·生产部署